使用Itext 进行PDf导出功能

时间:2021-04-13 22:18:16
  • 最近项目要用到pdf导出功能,这个功能此前一直都没接触过,最近通过Itext实现了,特此记录一下,方便日后需要。话不多说:

  • maven 依赖

<dependency>
      <groupId>com.itextpdf</groupId>
      <artifactId>itext-asian</artifactId>
      <version>5.2.0</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/com.itextpdf/itextpdf -->
    <dependency>
      <groupId>com.itextpdf</groupId>
      <artifactId>itextpdf</artifactId>
      <version>5.5.10</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/com.lowagie/itext -->
    <dependency>
      <groupId>com.lowagie</groupId>
      <artifactId>itext</artifactId>
      <version>2.1.7</version>
    </dependency>

这里使用的itext的版本不是最新的itext7,但是能够使用,完成功能。

  • 代码
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.origin.eurybia.utils.DateUtils;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;


public class ExportReportPdfUtil {

    /** * 报表导出功能 * * @param fileName * @param tableList * @param response * @throws Exception */
    public static void export(String fileName, List<PDFTable> tableList, HttpServletResponse response) throws Exception {
        Document document = new Document();

        BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        Font titFont = new Font(bfChinese, 20, Font.NORMAL);
        Font docFont = new Font(bfChinese, 12, Font.NORMAL);
        Font subTitle = new Font(bfChinese, 16, Font.NORMAL);
        Font footnoteFont = new Font(bfChinese, 10, Font.NORMAL);

        // 设置response参数,可以打开下载页面
        response.reset();
        response.setContentType("application/pdf;charset=utf-8");
        response.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("gb2312"), "ISO8859-1"));

        PdfWriter.getInstance(document, response.getOutputStream());

        //设置标题
        document.addTitle("XXXXX");
        //打开文档
        document.open();

        //设置title
        Paragraph header = new Paragraph("XXXXX", titFont);
        header.setAlignment(1);
        document.add(header);
        //设置报告出具时间
        Paragraph time = new Paragraph("【报告出具时间:" + DateUtils.formatDate(new Date(), "yyyy 年 MM 月 dd") + " 】", docFont);
        time.setIndentationLeft(300);
        document.add(time);

        for (PDFTable table : tableList) {
            Paragraph title = new Paragraph(table.getTitle(), subTitle);
            document.add(title);
            if (table.getTextDescription() != null) {
                Paragraph textDescription = new Paragraph(table.getTextDescription() + "\n", docFont);
                textDescription.setSpacingBefore(10f);
                textDescription.setIndentationLeft(50);
                document.add(textDescription);
            }
            if (table.getFootnote() != null) {
                Paragraph footnote = new Paragraph(table.getFootnote(), footnoteFont);
                footnote.setIndentationLeft(50);
                document.add(footnote);
            }
            PdfPTable conTable = new PdfPTable(table.getConWidths());
            conTable.setSpacingBefore(5f);
            conTable.setWidthPercentage(80);
            for (PDFColumn column : table.getColumns()) {
                PdfPCell cell = new PdfPCell(new Paragraph(column.getText(), docFont));
                if (column.isBold) {
                    cell.setBackgroundColor(BaseColor.LIGHT_GRAY);
                    cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                }
                cell.setSpaceCharRatio(10f);
                conTable.addCell(cell);
            }
            document.add(conTable);
        }

        String str = "\n" + "厂商确认(盖章)";
        Paragraph strGaiZhang = new Paragraph(str, titFont);
        strGaiZhang.setIndentationLeft(250);
        document.add(strGaiZhang);

        //关闭文档
        document.close();
    }
}

这里只是简单的一个实例,其中需要注意的是

BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);

这句主要是用来解决中文字体的问题,关于pdf上的文字的排版需要去查看API了,对于段前段后距离多少,居中还是距离左边的距离等都有相应的方法。

  • 这里的PDFTable和PDFColumn是自定义的表格JavaBean可以根据自己的需要自定义。
    PDFTable
import java.util.List;

/** * Created by silence on 2016/11/1. * Desc : */
public class PDFTable {
    private String title;
    private int numColumns;
    private float widthPercent;
    private List<PDFColumn> columns;
    private float[] conWidths;

    private String textDescription;
    private String footnote;

    public String getTextDescription() {
        return textDescription;
    }

    public void setTextDescription(String textDescription) {
        this.textDescription = textDescription;
    }

    public String getFootnote() {
        return footnote;
    }

    public void setFootnote(String footnote) {
        this.footnote = footnote;
    }

    public float[] getConWidths() {
        return conWidths;
    }

    public void setConWidths(float[] conWidths) {
        this.conWidths = conWidths;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public int getNumColumns() {
        return numColumns;
    }

    public void setNumColumns(int numColumns) {
        this.numColumns = numColumns;
    }

    public float getWidthPercent() {
        return widthPercent;
    }

    public void setWidthPercent(float widthPercent) {
        this.widthPercent = widthPercent;
    }

    public List<PDFColumn> getColumns() {
        return columns;
    }

    public void setColumns(List<PDFColumn> columns) {
        this.columns = columns;
    }
}

PDFColumn

/** * Created by silence on 2016/11/1. * Desc : */
public class PDFColumn {
    private String text;
    public boolean isBold = false;

    public boolean isHeader(){
        return false;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }
}

使用Itext 进行PDf导出功能