在Java代碼中使用iTextPDF生成PDF


1. 生成PDF

載入字體

    static {
        FontFactory.register("/fonts/msyh.ttf");
        FontFactory.register("/fonts/msyhbd.ttf");
        FontFactory.register("/fonts/simsun.ttc");
        FontFactory.register("/fonts/simhei.ttf");
    }

生成PDF

    Rectangle rectPageSize = new Rectangle(PageSize.A4);// A4紙張
        Document document = new Document(rectPageSize, 40, 40, 40, 40);// 上、下、左、右間距
        try {
            String filePath = StaticConfig.getConfig("file_path") + invest.getContractPath();
            String folderPath = filePath.substring(0, filePath.lastIndexOf("/") + 1);
            File folder = new File(folderPath);
            if (!folder.exists()) {
                folder.mkdirs();
            }

            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filePath));
            writer.setPdfVersion(PdfWriter.PDF_VERSION_1_7);
            document.addCreationDate();
            document.addCreator("rockbb");
            document.addTitle("rockbbPDF");
            document.addKeywords("export");
            document.addSubject("rockbb業務文件");
            document.open();
            Font yahei9px = FontFactory.getFont("微軟雅黑", BaseFont.IDENTITY_H, 9);
            Font yahei10px = FontFactory.getFont("微軟雅黑", BaseFont.IDENTITY_H, 10);
            Font yahei11px = FontFactory.getFont("微軟雅黑", BaseFont.IDENTITY_H, 11);
            Font yahei12px = FontFactory.getFont("微軟雅黑", BaseFont.IDENTITY_H, 12);

            document.add(paragraph("編號:[" + invest.getContractSn() + "]", yahei9px, Paragraph.ALIGN_RIGHT));

            //表格
            PdfPTable table = new PdfPTable(3);
            table.setSpacingBefore(10.0f);
            table.setWidthPercentage(100);
            table.setWidths(new float[]{0.25f, 0.25f, 0.5f});

            PdfPCell cell = cell("當事方", yahei11px, Element.ALIGN_CENTER, Element.ALIGN_MIDDLE);
            cell.setColspan(3);
            table.addCell(cell);

            cell = cell("甲方(投資者)", yahei10px);
            cell.setRowspan(3);
            table.addCell(cell);
            table.addCell(cell("姓名", yahei10px));
            table.addCell(cell(user.getRealName(), yahei10px));
            table.addCell(cell("用戶ID", yahei10px));
            table.addCell(cell(user.getTel(), yahei10px));
            table.addCell(cell("身份證", yahei10px));
            table.addCell(cell(user.getIdNumber(), yahei10px));

            cell = cell("乙方", yahei10px);
            cell.setRowspan(3);
            table.addCell(cell);
            table.addCell(cell("名稱", yahei10px));
            table.addCell(cell("公司", yahei10px));
            table.addCell(cell("住所", yahei10px));
            table.addCell(cell("北京市朝陽區", yahei10px));
            table.addCell(cell("注冊證", yahei10px));
            table.addCell(cell("", yahei10px));
            document.add(table);

            document.add(paragraph("* 凡本協議未列示的產品信息以平台產品說明書頁面顯示的產品具體信息為准。", yahei9px));

            document.add(paragraph("第二部分  協議條款", yahei12px, Paragraph.ALIGN_LEFT, 10.0f));

            document.add(paragraph(agreement, yahei10px, Paragraph.ALIGN_LEFT, 5.0f));

            document.close();
            writer.close();

        } catch (FileNotFoundException e) {
            logger.error("FileNotFoundException");
            logger.debug(e.getMessage(), e);
        } catch (IOException e) {
            logger.error("IOException");
            logger.debug(e.getMessage(), e);
        } catch (DocumentException e) {
            logger.error("DocumentException");
            logger.debug(e.getMessage(), e);
        }

工具方法

    private static PdfPCell cell(String content, Font font) {
        PdfPCell cell = new PdfPCell(new Phrase(content, font));
        cell.setBorderColor(new BaseColor(196, 196, 196));
        cell.setPadding(5.0f);
        cell.setPaddingTop(1.0f);
        return cell;
    }

    private static PdfPCell cell(String content, Font font, int hAlign, int vAlign) {
        PdfPCell cell = new PdfPCell(new Phrase(content, font));
        cell.setBorderColor(new BaseColor(196, 196, 196));
        cell.setVerticalAlignment(vAlign);
        cell.setHorizontalAlignment(hAlign);
        cell.setPadding(5.0f);
        cell.setPaddingTop(1.0f);
        return cell;
    }

    private static Paragraph paragraph(String content, Font font) {
        return new Paragraph(content, font);
    }

    private static Paragraph paragraph(String content, Font font, int hAlign) {
        Paragraph paragraph = new Paragraph(content, font);
        paragraph.setAlignment(hAlign);
        return paragraph;
    }

    private static Paragraph paragraph(String content, Font font, int hAlign, float spacingBefore) {
        Paragraph paragraph = new Paragraph(content, font);
        paragraph.setAlignment(hAlign);
        paragraph.setSpacingBefore(spacingBefore);
        return paragraph;
    }

在生成過程中加蓋圖片, 注意, 因為無法指定頁碼, 所以這段代碼要放到你需要加蓋圖片的那頁對應的代碼上

            byte[] bytes = FileUtil.readResourceImage("/text/stamp.png");
            if (bytes != null) {
                Image image = Image.getInstance(bytes);
                PdfContentByte canvas = writer.getDirectContent();
                writer.getPageNumber();
                // float width = image.getScaledWidth();
                // float height = image.getScaledHeight();
                canvas.addImage(image, 150, 0, 0, 150, rectPageSize.getWidth() - 300, rectPageSize.getHeight() - 300);
            } else {
                logger.error("Failed to read /text/stamp.png");
            }

讀取項目資源文件的工具方法

    /**
     * 讀取項目圖片資源文件
     *
     * @param filePath 以'/'開頭的項目資源文件路徑
     * @return
     */
    public static byte[] readResourceImage(String filePath) {
        try {
            InputStream is = FileUtil.class.getResourceAsStream(filePath);
            BufferedImage image = ImageIO.read(is);
            is.close();
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            ImageIO.write(image, "png", os);
            return os.toByteArray();
        } catch (FileNotFoundException e) {
            logger.error("FileNotFoundException: " + filePath);
        } catch (IOException e) {
            logger.error("IOException");
        }
        return null;
    }

    /**
     * 讀取項目資源文件內容
     *
     * @param filePath 以'/'開頭的項目資源文件路徑
     * @return 文件內容
     */
    public static String readResourceContent(String filePath) {
        StringBuilder sb = new StringBuilder();
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(FileUtil.class.getResourceAsStream(filePath)));
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
                sb.append("\n");
            }
            reader.close();
        } catch (FileNotFoundException e) {
            logger.error("FileNotFoundException: " + filePath);
        } catch (IOException e) {
            logger.error("IOException");
        }
        return sb.toString();
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM