【匯出PDF-專案應用】

我是太陽啦啦啦發表於2018-08-12

前言

  最近專案中用到了匯出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<Integer, String> 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<Integer, String> 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<Integer, String> 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<Integer, String> 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<Map<String, Object>> results= this.queryRepairOrder(request, response);
            if(results.size() >0) {


                Map<String, List<Map<String, Object>>> reset = new HashMap<>();
                Map<String, Map<String, Object>> id2pub = new HashMap<>();
                for (Map<String, Object> each : results) {
                    if (null == each) {
                        continue;
                    }
                    if ((null == each.get("id")) || "".equals(each.get("id"))) {
                        continue;
                    }
                    List<Map<String, Object>> 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<String, Object> x = new HashMap<>();
                    if (!id2pub.containsKey(each.get("id").toString())) {
                        id2pub.put(each.get("id").toString(), each);
                    }
                }
                int pageIndex = 1;
                for (Map.Entry<String, List<Map<String, Object>>> 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<String, Object> eachObj : eachMap.getValue()) {
                        for (Map.Entry<Integer, String> 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<String, Object> 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();
    }

總結

  在專案中不斷的成長.

相關文章