# Itext Pdf 生成相关API

Posted 爱码代码的喵

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了# Itext Pdf 生成相关API相关的知识,希望对你有一定的参考价值。

Itext Pdf 生成、相关API

需求

  • 需求java代码生成PDF效果如下:后端生成 Pdf文件,内容包含基本信息表格,图片、pdf需要有页眉,pdf每页含有页码,pdf含有多页。
  • 上图看看最后生成的效果如下:

功能实现

  • 使用 ItextPdf

引入依赖

  • 引入下面的依赖
<!-- itextpdf -->
<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.5.13.3</version>
</dependency>
<!-- pdf 中文支持 -->
<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itext-asian</artifactId>
    <version>5.2.0</version>
</dependency>

注意点

表格双边线的实现

  • 双边线的实现思路:使用多层单元格嵌套的效果显示所有单元格的边框

页眉和页码的实现

  • 继承PdfPageEventHelper重写对应的方法,在响应的方法中完成相关逻辑。

代码

  • ItextPdfUtils.java
public class ItextPdfUtils 

    private static final Logger logger = LoggerFactory.getLogger(ItextPdfUtils.class);
    public static final int TWENTY = 20;
    public static final int Thirty = 30;
    public static final int TWELVE = 12;

    /**
     * 中文字体,解决中文不能显示问题
     */
    public static BaseFont baseFontChinese = null;
    public static Font font = null;
    public static Font blueFont = null;
    public static Font smallThreeFont = null;
    public static Font fiveFont = null;
    public static Font smallFiveFont = null;
    public static Font smallSixFont = null;
    public static Font greenFont = null;
    public static Font messFont = null;
    public static Font titleFont = null;

    static 
        try 
            baseFontChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            font = new Font(baseFontChinese);
            font.setSize(10);
            blueFont = new Font(baseFontChinese);
            blueFont.setColor(BaseColor.BLUE);
            blueFont.setSize(5);
            smallThreeFont = new Font(baseFontChinese, TWENTY);
            smallThreeFont.setColor(BaseColor.BLACK);
            fiveFont = new Font(baseFontChinese);
            fiveFont.setColor(BaseColor.BLACK);
            fiveFont.setSize(10.5f);
            smallFiveFont = new Font(baseFontChinese);
            smallFiveFont.setColor(BaseColor.BLACK);
            smallFiveFont.setSize(9);
            smallSixFont = new Font(baseFontChinese);
            smallSixFont.setColor(BaseColor.BLACK);
            smallSixFont.setSize(6.5f);
            greenFont = new Font(baseFontChinese, TWELVE, Font.BOLD);
            greenFont.setColor(BaseColor.BLACK);
            messFont = new Font(baseFontChinese, 12);
            messFont.setColor(BaseColor.BLACK);
            titleFont = new Font(baseFontChinese, 14, Font.BOLD);
            titleFont.setColor(BaseColor.BLACK);
         catch (Exception e) 
            logger.error("Error Occur:0", e);
        
    

    /**
     * pdf 页面生成
     *
     * @param writer
     * @param yeMei
     * @param fontSize
     * @param pageSize
     */
    public static void setFooter(PdfWriter writer, String yeMei, int fontSize, Rectangle pageSize) 
        ItextPdfHeaderFooter headerFooter = new ItextPdfHeaderFooter(yeMei, pageSize);
        writer.setPageEvent(headerFooter);
    


    public static PdfPCell getCell(String title, Font font, int miniMumHeight, int alignMiddle) 
        PdfPCell pdfPCell;
        pdfPCell = new PdfPCell(new Phrase(title, font));
        pdfPCell.setMinimumHeight(miniMumHeight);
        pdfPCell.setVerticalAlignment(alignMiddle);
        return pdfPCell;
    

    public static PdfPCell getCell(String title, Font font, int miniMumHeight) 
        PdfPCell pdfPCell;
        pdfPCell = new PdfPCell(new Phrase(title, font));
        pdfPCell.setMinimumHeight(miniMumHeight);
        return pdfPCell;
    

    public static PdfPCell getCell(String title, Font font, int miniMumHeight, boolean useAscender, int horizontalAlignment, int verticalAlignment) 
        PdfPCell pdfPCell;
        pdfPCell = new PdfPCell(new Phrase(title, font));
        pdfPCell.setUseAscender(useAscender);
        pdfPCell.setMinimumHeight(miniMumHeight);
        pdfPCell.setVerticalAlignment(verticalAlignment);
        pdfPCell.setHorizontalAlignment(horizontalAlignment);
        return pdfPCell;
    

    public static PdfPCell getCell(String title, Font font, int miniMumHeight, boolean useAscender, int horizontalAlignment, int verticalAlignment, int colSpan) 
        PdfPCell pdfPCell;
        pdfPCell = new PdfPCell(new Phrase(title, font));
        pdfPCell.setUseAscender(useAscender);
        pdfPCell.setMinimumHeight(miniMumHeight);
        pdfPCell.setVerticalAlignment(verticalAlignment);
        pdfPCell.setHorizontalAlignment(horizontalAlignment);
        pdfPCell.setColspan(colSpan);
        return pdfPCell;
    

    public static PdfPCell getCell(String title, Font font, Integer miniMumHeight, Boolean useAscender, Integer horizontalAlignment, Integer verticalAlignment, Integer colSpan, Integer rowSpan, Integer border, Integer borderWidthTop, Integer borderWidthLeft, Integer borderWidthRight) 
        Phrase phrase = new Phrase(title, font);
        PdfPCell pdfPCell = new PdfPCell(phrase);
        if (Objects.nonNull(miniMumHeight)) 
            pdfPCell.setMinimumHeight(miniMumHeight);
        
        if (Objects.nonNull(useAscender)) 
            pdfPCell.setUseAscender(useAscender);
        
        if (Objects.nonNull(horizontalAlignment)) 
            pdfPCell.setHorizontalAlignment(horizontalAlignment);
        
        if (Objects.nonNull(verticalAlignment)) 
            pdfPCell.setVerticalAlignment(verticalAlignment);
        
        if (Objects.nonNull(colSpan)) 
            pdfPCell.setColspan(colSpan);
        
        if (Objects.nonNull(rowSpan)) 
            pdfPCell.setRowspan(rowSpan);
        
        if (Objects.nonNull(border)) 
            pdfPCell.setBorder(border);
        
        if (Objects.nonNull(borderWidthTop)) 
            pdfPCell.setBorderWidthTop(borderWidthTop);
        
        if (Objects.nonNull(borderWidthLeft)) 
            pdfPCell.setBorderWidthLeft(borderWidthLeft);
        
        if (Objects.nonNull(borderWidthRight)) 
            pdfPCell.setBorderWidthRight(borderWidthRight);
        
        return pdfPCell;
    

  • ItextPdfTest.java
public class ItextPdfTest 

    private static final Logger logger = LoggerFactory.getLogger(ItextPdfUtils.class);

    private static final float[] columnWidths5 = 0.5f, 0.5f, 0.5f, 0.5f, 0.5f;

    /**
     * 生成 ItextPdf
     *
     * @return String
     */
    private String createItextPdf() 
        Date date = new Date();
        String startTime = new SimpleDateFormat("yyyyMMddHHmmss").format(date);
        String fileName = "demo";
        String oldPath = fileName + ".pdf";
        // 创建文件
        Document document = new Document();
        PdfWriter writer = null;
        try 
            document.setPageSize(PageSize.A4);
            // 建立一个书写器
            writer = PdfWriter.getInstance(document, new FileOutputStream(oldPath));
            ItextPdfUtils.setFooter(writer, "测试页眉", 12, PageSize.LEGAL);
            // 打开文件
            document.open();

            // 总表设计一个 4 列的表.
            PdfPTable table = new PdfPTable(4);
            table.setWidthPercentage(100);
            table.setSpacingBefore(100f);
            table.setSpacingAfter(10f);

            // 设置列宽
            float[] columnWidths = 0.8f, 0.8f, 0.5f, 0.5f;
            table.setWidths(columnWidths);

            PdfPCell cell;
            // 第一行
            table.addCell(ItextPdfUtils.getCell("", null, TWENTY, true, Cell.ALIGN_CENTER, Cell.ALIGN_MIDDLE, 0, null, 0, 0, 0, 0));
            table.addCell(ItextPdfUtils.getCell("ItextPdf 打印测试", smallThreeFont, TWENTY, true, Cell.ALIGN_CENTER, Cell.ALIGN_MIDDLE, 0, null, 0, 0, 0, 0));
            table.addCell(ItextPdfUtils.getCell("", fiveFont, TWENTY, true, Cell.ALIGN_RIGHT, Cell.ALIGN_BOTTOM, 2, null, 0, null, null, null));
            // 第三行
            table.addCell(ItextPdfUtils.getCell("记录人:张三", fiveFont, TWENTY, true, Cell.ALIGN_LEFT, Cell.ALIGN_MIDDLE, 0, null, 0, null, null, null));
            table.addCell(ItextPdfUtils.getCell("打印日期:" + new SimpleDateFormat("yyyy-MM-dd HH-mm-ss").format(new Date()), fiveFont, TWENTY, true, Cell.ALIGN_CENTER, Cell.ALIGN_MIDDLE, 0, null, 0, null, null, null));
            table.addCell(ItextPdfUtils.getCell("编号:AAAAAAAAAAAAA号", fiveFont, TWENTY, true, Cell.ALIGN_RIGHT, Cell.ALIGN_MIDDLE, 2, null, 0, null, null, null));

            // 第一个表格
            PdfPTable personInfoTable = new PdfPTable(5);
            float[] headerTableColumnWidth = 0.5f, 0.5f, 0.5f, 0.5f, 0.5f;
            personInfoTable.setWidthPercentage(100);
            personInfoTable.setWidths(headerTableColumnWidth);
            personInfoTable.addCell(ItextPdfUtils.getCell("编号", fiveFont, Thirty, Cell.ALIGN_MIDDLE));
            personInfoTable.addCell(ItextPdfUtils.getCell("", fiveFont, Thirty, Cell.ALIGN_MIDDLE));
            personInfoTable.addCell(ItextPdfUtils.getCell("姓名", fiveFont, Thirty, Cell.ALIGN_MIDDLE));
            personInfoTable.addCell(ItextPdfUtils.getCell("", fiveFont, Thirty, Cell.ALIGN_MIDDLE));

            Image img = Image.getInstance("demo.jpg");
            PdfPCell imageCell = new PdfPCell(new Phrase("照片", fiveFont));
            imageCell.setVerticalAlignment(Cell.ALIGN_MIDDLE);
            imageCell.setHorizontalAlignment(Cell.ALIGN_CENTER);
            imageCell.setRowspan(4);
            imageCell.setImage(img);
            personInfoTable.addCell(imageCell);
            personInfoTable.addCell(ItextPdfUtils.getCell("性别", fiveFont, Thirty, Cell.ALIGN_MIDDLE));
            personInfoTable.addCell(ItextPdfUtils.getCell("", fiveFont, Thirty, Cell.ALIGN_MIDDLE));
            personInfoTable.addCell(ItextPdfUtils.getCell("籍贯", fiveFont, Thirty, Cell.ALIGN_MIDDLE));
            personInfoTable.addCell(ItextPdfUtils.getCell("", fiveFont, Thirty, Cell.ALIGN_MIDDLE));
            personInfoTable.addCell(ItextPdfUtils.getCell("民族", fiveFont, Thirty, Cell.ALIGN_MIDDLE));
            personInfoTable.addCell(ItextPdfUtils.getCell("", fiveFont, Thirty, Cell.ALIGN_MIDDLE));
            personInfoTable.addCell(Itex

以上是关于# Itext Pdf 生成相关API的主要内容,如果未能解决你的问题,请参考以下文章

itext生成PDF,天坑

使用itext获取pdf模板,生成pdf

如何运用Java组件itext生成pdf

如何运用Java组件itext生成pdf

java使用iText生成pdf表格

利用Java动态生成 PDF 文档