【导出PDF-项目应用】

前言

  最近项目中用到了导出PDF,所以在这里总结一下,便于以后的查阅.也在这里分享给看到博客的伙伴们

核心

代码展示:

public void exportpdf(HttpServletRequest request, HttpServletResponse response) {
        String strAppRootPath = request.getServletContext().getRealPath("/");
        String title = "LDAR维修工单";

        // 导出文件名
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        String fileName = formatter.format(System.currentTimeMillis()) + ".pdf";

        Map dicTitleUp = new HashMap<>();
        dicTitleUp.put(0, "组件号");
        dicTitleUp.put(1, "装置");
        dicTitleUp.put(2, "区域");
        dicTitleUp.put(3, "设备");
        dicTitleUp.put(4, "组件类型");
        dicTitleUp.put(5, "组件子类型");
        dicTitleUp.put(6, "位置描述");
        dicTitleUp.put(7, "尺寸(mm)");
        dicTitleUp.put(8, "PID图号");
        dicTitleUp.put(9, "检测日期");
        dicTitleUp.put(10, "检测人");
        dicTitleUp.put(11, "PPM读数");
        dicTitleUp.put(12, "泄漏阈值");
        dicTitleUp.put(13, "泄漏源");
        dicTitleUp.put(14, "首次修复期限");
        dicTitleUp.put(15, "最终修复期限");
        dicTitleUp.put(16, "到期时间");
        dicTitleUp.put(17, "延迟修复的预期日期");



        Map dicUp = new HashMap<>();
        dicUp.put(0, "COMPONENT_NUMBER");
        dicUp.put(1, "LOCATIONA_NAME");
        dicUp.put(2, "LOCATIONB_NAME");
        dicUp.put(3, "LOCATIONC_NAME");
        dicUp.put(4, "COMPONENT_TYPE_NAME");
        dicUp.put(5, "SUB_TYPE_NAME");
        dicUp.put(6, "LOCATION_DESCRIPTION");
        dicUp.put(7, "SIZE_OF");
        dicUp.put(8, "DRAWING");
        dicUp.put(9, "DATETIMESTART");
        dicUp.put(10, "realname");
        dicUp.put(11, "READING");
        dicUp.put(12, "FINAL_THRESHOLD");
        dicUp.put(13, "leakage_source_name");
        dicUp.put(14, "FIRST_TIME_LIMIT");
        dicUp.put(15, "LAST_TIME_LIMIT");
        dicUp.put(16, "due");
        dicUp.put(17, "expeted");

        // 下面的表格
        Map dicTitle = new HashMap<>();
        dicTitle.put(0, "维修日期");
        dicTitle.put(1, "维修人");
        dicTitle.put(2, "维修措施");
        dicTitle.put(3, "复检日期");
        dicTitle.put(4, "检测人");
        dicTitle.put(5, "仪器");
        dicTitle.put(6, "背景值");
        dicTitle.put(7, "PPM读数");

        Map dic = new HashMap<>();
        dic.put(0, "maintenance_date");
        dic.put(1, "maintenance_name");
        dic.put(2, "maintenance_measures_name");
        dic.put(3, "retest_start_date");
        dic.put(4, "retest_name");
        dic.put(5, "testing_instrument_name");
        dic.put(6, "background_ppm_readings");
        dic.put(7, "ppm_readings");

        Rectangle rect = new Rectangle(PageSize.A4);
        Document document = new Document(rect);
        OutputStream os = null;
        try {
            String type = "pdf";
            this.setResponseHeader(response, fileName ,type);
            os = response.getOutputStream();
            PdfWriter writer = PdfWriter.getInstance(document, os);
            document.open();

            BaseFont bfChinese  = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", false);
            Font fontTitle = new Font(bfChinese, 22.0F, 0);
            Font exportMan = new Font(bfChinese, 14.0F, 0);
            Font cont = new Font(bfChinese, 10.0F, 0);
            Font s = new Font(bfChinese, 10.0F, 0);
            //查询的数据
            List> results= this.queryRepairOrder(request, response);
            if(results.size() >0) {


                Map>> reset = new HashMap<>();
                Map> id2pub = new HashMap<>();
                for (Map each : results) {
                    if (null == each) {
                        continue;
                    }
                    if ((null == each.get("id")) || "".equals(each.get("id"))) {
                        continue;
                    }
                    List> subList = new ArrayList<>();
                    if (!reset.containsKey(each.get("id").toString())) {
                        reset.put(each.get("id").toString(), subList);
                    }
                    subList = reset.get(each.get("id").toString());
                    subList.add(each);

                    Map x = new HashMap<>();
                    if (!id2pub.containsKey(each.get("id").toString())) {
                        id2pub.put(each.get("id").toString(), each);
                    }
                }
                int pageIndex = 1;
                for (Map.Entry>> eachMap : reset.entrySet()) {

                    for (int i = 0; i < 3; i++) {
                        document.add(new Paragraph("\n"));
                    }
                    //logo图片
                    String logoPath = "upload\\files\\20171012\\logo.png";
                    logoPath = strAppRootPath + logoPath;
                    logoPath = logoPath.replace("/", File.separator).replace("\\", File.separator);
                    Image image = Image.getInstance(logoPath);
                    image.setAbsolutePosition(420, 730);
                    float wid = image.getWidth();
                    float hei = image.getHeight();
                    image.scaleAbsolute(wid, hei);
                    document.add(image);
                    // 标题
                    Paragraph tit = new Paragraph(title, fontTitle);
                    tit.setAlignment(Element.ALIGN_CENTER);
                    tit.setLeading(1f);
                    document.add(tit);
                    document.add(new Paragraph("\n"));
                    // 导出人
                    //String name = "导出人:" + ResourceUtil.getSessionUser().getRealName();
                    String name = "中天合创";
                    Paragraph export = new Paragraph(name, exportMan);
                    export.setAlignment(Element.ALIGN_CENTER);
                    tit.setLeading(1f);
                    document.add(export);
                    document.add(new Paragraph("\n"));

                    // 上半部分
                    PdfPTable upTable = new PdfPTable(4);
                    upTable.setTotalWidth(100);
                    upTable.setWidths(new float[]{15f, 35f, 15f, 35f});
                    upTable.setWidthPercentage(100.0F);
                    upTable.setHeaderRows(1);
                    upTable.getDefaultCell().setHorizontalAlignment(1);
                    upTable.setSpacingBefore(10f); // 前间距
                    upTable.setSpacingAfter(10f); // 后间距

                    String content = "";
                    int valIndex = 0;
                    int cellIndex = 0;

                    for (int len = 0; len < dicTitleUp.size() / 2 + dicTitleUp.size() % 2; len++) {
                        PdfPCell cell = null;
                        for (int i = 0; i < 4; i++) {
                            if (i == 0 || i == 2) {
                                content = dicTitleUp.get(cellIndex);
                                cell = new PdfPCell(new Paragraph(content, cont));
                                alignLeft(cell);
                                cellIndex++;
                            } else if (null == id2pub.get(eachMap.getKey()).get(dicUp.get(valIndex))) {
                                content = "";
                                cell = new PdfPCell(new Paragraph(content, cont));
                                alignRight(cell);

                                valIndex++;

                            } else {
                                content = id2pub.get(eachMap.getKey()).get(dicUp.get(valIndex)).toString();
                                cell = new PdfPCell(new Paragraph(content, cont));
                                alignRight(cell);
                                valIndex++;
                            }

                            upTable.addCell(cell);
                        }
                    }
                    document.add(upTable);
                    //下半部分
                    PdfPTable bottomTable = new PdfPTable(8);
                    bottomTable.setTotalWidth(100);
                    bottomTable.setWidths(new float[]{13f, 14f, 12f, 13f, 13f, 10f, 14f, 13f});
                    bottomTable.setWidthPercentage(100.0F);
                    bottomTable.setHeaderRows(1);
                    bottomTable.getDefaultCell().setHorizontalAlignment(1);
                    bottomTable.setSpacingBefore(10f); // 前间距
                    bottomTable.setSpacingAfter(10f); // 后间距
                    //填充表头
                    PdfPCell cell = null;
                    for (int valueIndex = 0; valueIndex < dicTitle.size(); valueIndex++) {
                        cell = new PdfPCell(new Paragraph(dicTitle.get(valueIndex), cont));
                        alignCenter(cell);
                        bottomTable.addCell(cell);
                    }
                    // 填充内容
                    int rowIndex = 0;
                    PdfPCell cell2 = null;

                    for (Map eachObj : eachMap.getValue()) {
                        for (Map.Entry each2 : dic.entrySet()) {
                            if (null != each2.getValue() && null != eachObj.get(each2.getValue())) {
                                content = eachObj.get(each2.getValue()).toString();
                            } else {
                                content = "";
                            }
                            cell2 = new PdfPCell(new Paragraph(content, cont));
                            alignCenter(cell2);
                            bottomTable.addCell(cell2);
                        }
                        rowIndex++;
                    }
                    int a = 2;
                    for (int k = rowIndex; k < a; k++) {
                        for (int index = 0; index < dicTitle.size(); index++) {
                            content = "";
                            cell2 = new PdfPCell(new Paragraph(content, cont));
                            alignCenter(cell2);
                            bottomTable.addCell(cell2);
                        }
                    }
                    document.add(bottomTable);
                    //图片部分
                    PdfPTable imageTable = new PdfPTable(4);
                    imageTable.setTotalWidth(100);
                    imageTable.setWidths(new float[]{10f, 30f, 30f, 30f});
                    imageTable.setWidthPercentage(100.0F);

                    String path = "";
                    float h = 120f;
                    for (Map eachObj : eachMap.getValue()) {
                        path = null == eachObj.get("MARK_PICTURES_ADDRESS") ? "" : eachObj.get("MARK_PICTURES_ADDRESS").toString();
                    }
                    content = "备注";
                    PdfPCell cellPic1 = new PdfPCell(new Paragraph(content, cont));
                    cellPic1.setFixedHeight(h);
                    content = strAppRootPath + path;
                    content = content.replace("/", File.separator).replace("\\", File.separator);
                    File file = new File(content);
                    if (!file.exists() || "".equals(path) || path == null) {
                        content = "";
                        PdfPCell cellPic2 = new PdfPCell(new Paragraph(content, cont));

                        PdfPCell cellPic3 = new PdfPCell(new Paragraph(content, cont));
                        cellPic3.setFixedHeight(h);
                        PdfPCell cellPic4 = new PdfPCell(new Paragraph(content, cont));
                        cellPic4.setFixedHeight(h);

                        imageTable.addCell(cellPic1);
                        imageTable.addCell(cellPic2);
                        imageTable.addCell(cellPic3);
                        imageTable.addCell(cellPic4);

                        document.add(imageTable);
                        document.add(new Paragraph("\n"));

                        footer(id2pub, document, s, pageIndex);
                        pageIndex++;
                        document.newPage();
                    } else {
                        Image imagex = Image.getInstance(content);
                        PdfPTable picTable = new PdfPTable(1);
                        picTable.addCell(imagex);
                        PdfPCell cellPic2 = new PdfPCell(picTable);

                        content = "";
                        PdfPCell cellPic3 = new PdfPCell(new Paragraph(content, cont));
                        cellPic3.setFixedHeight(h);
                        PdfPCell cellPic4 = new PdfPCell(new Paragraph(content, cont));
                        cellPic4.setFixedHeight(h);

                        imageTable.addCell(cellPic1);
                        imageTable.addCell(cellPic2);
                        imageTable.addCell(cellPic3);
                        imageTable.addCell(cellPic4);

                        document.add(imageTable);
                        document.add(new Paragraph("\n"));

                        footer(id2pub, document, s, pageIndex);
                        pageIndex++;

                        document.newPage();
                    }
                }
            }else{
                //logo图片
                String logoPath = "upload\\files\\20171012\\logo.png";
                logoPath = strAppRootPath + logoPath;
                logoPath = logoPath.replace("/", File.separator).replace("\\", File.separator);
                Image image = Image.getInstance(logoPath);
                image.setAbsolutePosition(420, 730);
                float wid = image.getWidth();
                float hei = image.getHeight();
                image.scaleAbsolute(wid, hei);
                document.add(image);
                // 标题
                Paragraph tit = new Paragraph(title, fontTitle);
                tit.setAlignment(Element.ALIGN_CENTER);
                tit.setLeading(1f);
                document.add(tit);
                document.add(new Paragraph("\n"));
                // 导出人
                //String name = "导出人:" + ResourceUtil.getSessionUser().getRealName();
                String name = "中天合创";
                Paragraph export = new Paragraph(name, exportMan);
                export.setAlignment(Element.ALIGN_CENTER);
                tit.setLeading(1f);
                document.add(export);
                document.add(new Paragraph("\n"));

            }
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        document.close();
    }

总结

  在项目中不断的成长.

你可能感兴趣的:(●【J2EE学习之旅】)