欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

itext生成pdf

程序员文章站 2024-03-24 11:42:40
...

itextpdf.5.5.0jar

      public void getpdf2(String path, ServerReport model) throws Exception {
    //要填入模本的数据文件
    Map<String, Object> datemap = getStringData(model);
    getStringData(model);
    String templatePath = "";
    // 模板路径
    if (model.getReporttype() == 0) {
        templatePath = "C:\\Users\\sunmiao\\Desktop\\reportTemplet.pdf";
    } else if (model.getReporttype() == 1) {
        templatePath = "E:/ideawork/ceservice/ceservice/ceservice3/src/com/ceservice\\document\\template\\patrolTemplet.pdf";
    }
    // 生成的新文件路径
    String newPDFPath = path;
    PdfReader reader;
    FileOutputStream out;
    ByteArrayOutputStream bos;
    PdfStamper stamper;
    try {
        System.setProperty("javax.xml.parsers.DocumentBuilderFactory", "com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl");
        BaseFont bf = BaseFont.createFont("E:\\ideawork\\ceservice\\ceservice\\ceservice3\\src\\com\\ceservice\\document\\template\\simsun.ttc,0", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        out = new FileOutputStream(newPDFPath);// 输出流
        reader = new PdfReader(templatePath);// 读取pdf模板
        bos = new ByteArrayOutputStream();
        stamper = new PdfStamper(reader, bos);
        AcroFields form = stamper.getAcroFields();
        form.addSubstitutionFont(bf);
        //文字类内容
        for (String key : datemap.keySet()) {
            String value = (String) datemap.get(key);
            form.setField(key, value);
        }
        // 图片类的内容处理
        Map<String, String> imgmap = getImageData(model);
        for (String key : imgmap.keySet()) {
            String value = imgmap.get(key);
            String imgpath = value;
            int pageNo = form.getFieldPositions(key).get(0).page;
            Rectangle signRect = form.getFieldPositions(key).get(0).position;
            float x = signRect.getLeft();
            float y = signRect.getBottom();
            // 根据路径读取图片
            Image image = Image.getInstance(imgpath);
            // 获取图片页面
            PdfContentByte under = stamper.getOverContent(pageNo);
            // 图片大小自适应
            image.scaleToFit(signRect.getWidth(), signRect.getHeight());
            // 添加图片
            image.setAbsolutePosition(x, y);
            under.addImage(image);
        }
        // 表格类
        Map<String, List<List<String>>> listMap = getListData(model);
        if(listMap.size()>0){
            for (String key : listMap.keySet()) {
                List<List<String>> lists = listMap.get(key);
                int pageNo = form.getFieldPositions(key).get(0).page;
                PdfContentByte pcb = stamper.getOverContent(pageNo);
                Rectangle signRect = form.getFieldPositions(key).get(0).position;
                //表格位置
                int column = lists.get(0).size();
                int row = lists.size();
                PdfPTable table = new PdfPTable(4);
                float tatalWidth = signRect.getRight() - signRect.getLeft() - 1;
                int size = lists.get(0).size();
                float width[] = new float[size];
                for (int i = 0; i < size; i++) {
                    if (i == 0) {
                        width[i] = 50f;
                    } else if (i==1){
                        width[i] = 90f;
                    }else if (i==2){
                        width[i] = (tatalWidth - 170);
                    }else{
                        width[i] = 30f;
                    }
                }
                table.setTotalWidth(width);
                table.setLockedWidth(true);
                table.setKeepTogether(true);
                table.setSplitLate(false);
                table.setSplitRows(true);
                Font FontProve = new Font(bf,5,0);
                //表格数据填写
                for (int i = 0; i < row; i++) {
                    List<String> list = lists.get(i);
                    for (int j = 0; j < column; j++) {
                        Paragraph paragraph = new Paragraph(String.valueOf(list.get(j)), FontProve);
                        PdfPCell cell = new PdfPCell(paragraph);
                        cell.setBorderWidth(1);
                        cell.setVerticalAlignment(Element.ALIGN_CENTER);
                        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                        cell.setLeading(0, (float) 1.4);
                        table.addCell(cell);
                    }
                }
                table.writeSelectedRows(0, -1, signRect.getLeft(), signRect.getTop(), pcb);
            }
        }
        stamper.setFormFlattening(true);// 如果为false,生成的PDF文件可以编辑,如果为true,生成的PDF文件不可以编辑
        stamper.close();
        Document doc = new Document();
        PdfCopy copy = new PdfCopy(doc, out);
        doc.open();
        PdfImportedPage importPage = null;
        ///循环是处理成品只显示一页的问题
        for (int i=1;i<=reader.getNumberOfPages();i++) {
            importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), i);
            copy.addPage(importPage);
        }
        doc.close();

    } catch (IOException e) {
        System.out.println(e);
    } catch (DocumentException e) {
        System.out.println(e);
    }

}

private Map<String, Object> getStringData(ServerReport model) {
    Map<String, Object> dataMap = new HashMap<String, Object>();
    dataMap.put("repartnum", model.getReportnum());
    dataMap.put("customname", model.getCustomername());
    dataMap.put("month", DateUtil.formatIso8601Day(model.getArrivetime()));
    dataMap.put("arrivetime", DateUtil.getDateShortLongTimeCn(model.getArrivetime()));
    dataMap.put("machinetype", model.getMachinetype());
    dataMap.put("leveltime", DateUtil.getDateShortLongTimeCn(model.getLeveltime()));
    dataMap.put("equipmentnum", model.getEquipmentnum());
    dataMap.put("servicetype", model.getServertype());
    dataMap.put("taskid", model.getTaskid());
    dataMap.put("k3num", model.getK3num());
    if (model.getDescribecon() != null) {
        dataMap.put("describecon", model.getDescribecon());
    }
    if ("现象描述".equals(model.getDescribetype())) {
        dataMap.put("describetype2", "flase");
        dataMap.put("describetype3", "flase");
    }
    if ("工作任务描述".equals(model.getDescribetype())) {
        dataMap.put("describetype1", "flase");
        dataMap.put("describetype3", "flase");
    }
    if ("其他".equals(model.getDescribetype())) {
        dataMap.put("describetype2", "flase");
        dataMap.put("describetype1", "flase");
    }

    if (model.getWorkstep() != null) {
        dataMap.put("workstep", model.getWorkstep());
    }
    if (model.getSuccesswork() != null) {
        dataMap.put("successwork", model.getSuccesswork());
    }
    if (model.getAwaitwork() != null) {
        dataMap.put("awaitwork", model.getAwaitwork());
    }
    if (StringUtil.checkNotNull(model.getOpinion())) {
        dataMap.put("opinion", model.getOpinion());
    }
    if (model.getRemark() != null) {
        dataMap.put("remark", model.getRemark());
    }

    if ("满意".equals(model.getTechnologyappraise())) {
        dataMap.put("technologyappraise2", "flase");
        dataMap.put("technologyappraise3", "flase");
    }
    if ("比较满意".equals(model.getTechnologyappraise())) {
        dataMap.put("technologyappraise1", "flase");
        dataMap.put("technologyappraise3", "flase");
    }
    if ("有待改进".equals(model.getTechnologyappraise())) {
        dataMap.put("technologyappraise2", "flase");
        dataMap.put("technologyappraise1", "flase");
    }
    if ("满意".equals(model.getFeedbackappraise())) {
        dataMap.put("feedbackappraise2", "flase");
        dataMap.put("feedbackappraise3", "flase");
    }
    if ("比较满意".equals(model.getFeedbackappraise())) {
        dataMap.put("feedbackappraise1", "flase");
        dataMap.put("feedbackappraise3", "flase");
    }
    if ("有待改进".equals(model.getFeedbackappraise())) {
        dataMap.put("feedbackappraise2", "flase");
        dataMap.put("feedbackappraise1", "flase");
    }
    dataMap.put("customeradvice", model.getCustomeradvice());

    dataMap.put("customersigntime", DateUtil.getDateLongCn(model.getCustomersigntime()));
    dataMap.put("employeesigntime", DateUtil.getDateLongCn(model.getEmployeesigntime()));

    if (model.getArrivetime() != null && model.getLeveltime() != null) {
        double serviceTime = model.getLeveltime().getTime() - model.getArrivetime().getTime();
        dataMap.put("serviceTime", String.format("%.1f", serviceTime / (60 * 60 * 1000)));
    }

    ReportExt ext = model.getReportExt();
    if (ext != null) {
        if (ext.getSysdescribe() != null) {
            dataMap.put("sys", ext.getSysdescribe());
        }
        if (ext.getCondescribe() != null) {
            dataMap.put("con", ext.getCondescribe());
        }
        if (ext.getDetail() != null) {
            dataMap.put("detail", ext.getDetail());
        }
        if (ext.getNormal() != null) {
            dataMap.put("normal", String.valueOf(ext.getNormal()));
        }
        if (ext.getProblem() != null) {
            dataMap.put("problem", String.valueOf(ext.getProblem()));
        }

        if (ext.getProblem() != null && ext.getNormal() != null) {
            dataMap.put("total", String.valueOf(ext.getProblem() + ext.getNormal()));
        }

    }
    Map<String, String> newFeedbackImgMap = model.getNewFeedbackImgMap();
    if (newFeedbackImgMap != null && newFeedbackImgMap.size() != 0) {
        Set<String> names = model.getNewFeedbackImgMap().keySet();
        int count=1;
        for(String name:names){
            dataMap.put("ImageName"+count+"", name);
            count++;
        }
    }
    if (model.getOldFeedbackImgMap() != null && model.getOldFeedbackImgMap().size() != 0) {
        Set<String> names = model.getOldFeedbackImgMap().keySet();
        int count=1;
        for(String name:names){
            dataMap.put("oldImageName"+count+"", name);
            count++;
        }
    }
    return dataMap;
}

private Map<String, String> getImageData(ServerReport model) {
    Map<String, String> imgMap = new HashMap<String, String>();
    if (StringUtil.checkNotNull(model.getEmployeesignpath())) {
        imgMap.put("emppath", model.getEmployeesignpath());
    }
    if (StringUtil.checkNotNull(model.getCustomersignpath())) {
        imgMap.put("cuspath", model.getCustomersignpath());
    }
    Map<String, String> newFeedbackImgMap = model.getNewFeedbackImgMap();
    if (newFeedbackImgMap != null && newFeedbackImgMap.size() != 0) {
        Set<String> names = model.getNewFeedbackImgMap().keySet();
        int count=1;
        for(String name:names){
            imgMap.put("newImage"+count+"", newFeedbackImgMap.get(name));
            count++;
        }
    }
    if (model.getOldFeedbackImgMap() != null && model.getOldFeedbackImgMap().size() != 0) {
        Set<String> names = model.getNewFeedbackImgMap().keySet();
        int count=1;
        for(String name:names){
            imgMap.put("oldImage"+count+"", newFeedbackImgMap.get(name));
            count++;
        }
    }
    return imgMap;
}

private Map<String, List<List<String>>> getListData(ServerReport model) {
    Map<String, List<List<String>>> listMap = new HashMap<String, List<List<String>>>();
    List<String> list = new ArrayList<String>();
    list.add("备件名称");
    list.add("PN/FRU");
    list.add("备件SN");
    list.add("数量");
    List<List<String>> newList = new ArrayList<List<String>>();
    List<List<String>> oldList = new ArrayList<List<String>>();
    newList.add(list);
    if (model.getItems() != null && model.getItems().size() != 0) {
        for(RequestItem newItem:model.getItems()){
            List<String> list2 = new ArrayList<String>();
            list2.add(newItem.getSupplies().getName());
            list2.add(newItem.getSupplies().getPn());
            list2.add(newItem.getSupplies().getSn());
            list2.add(String.valueOf(newItem.getRequestnumber()));
            newList.add(list2);
        }
    }
    oldList.add(list);
    if (model.getOlditems() != null && model.getOlditems().size() != 0) {
        for(RequestItem oldItem:model.getOlditems()){
            List<String> list3 = new ArrayList<String>();
            list3.add(oldItem.getSupplies().getName());
            list3.add(oldItem.getSupplies().getPn());
            list3.add(oldItem.getSupplies().getSn());
            list3.add(String.valueOf(oldItem.getRequestnumber()));
            oldList.add(list3);
        }
    }
    listMap.put("newList", newList);
    listMap.put("oldList", oldList);
    return listMap;
}