1.在pom引入jra包
<!--itext的jar包 生成pdf 兼容linux windows-->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.10</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
<dependency>
<groupId>com.itextpdf.tool</groupId>
<artifactId>xmlworker</artifactId>
<version>5.4.1</version>
</dependency>
2.导出模板(util文件)
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import lombok.extern.slf4j.Slf4j;
import java.io.File;
import java.io.FileOutputStream;
import java.util.LinkedHashMap;
import java.util.List;
@Slf4j
public class SSWToPdf extends PdfPageEventHelper {
public void createOutsourcingAuditBillsPDF(String billMonth, List<LinkedHashMap<String, Object>> taskStatusList, String pdfPath, String fileName) throws Exception {
// 1.新建document对象
Document document = new Document(PageSize.A4, 0, 0, 60, 50);
File pdfFile = new File(pdfPath);
if (!pdfFile.exists()) {
pdfFile.mkdirs();
}
// 2.建立一个书写器(Writer)与document对象关联,通过书写器(Writer)可以将文档写入到磁盘中。
// 创建 PdfWriter 对象 第一个参数是对文档对象的引用,第二个参数是文件的实际名称,在该名称中还会给出其输出路径。
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(pdfPath + fileName));
//设置字体
BaseFont bfChinese1 = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
Font FontChinese10Color = new Font(bfChinese1, 10, Font.NORMAL, new BaseColor(231, 24, 55));
Font FontChinese10Normal = new Font(bfChinese1, 10, Font.NORMAL);
//writer.setPageEvent(new PdfPageHelper("外包供应商月度账单","外包审计账单",billMonth));
// 3.打开文档
document.open();
PdfPTable table = new PdfPTable(7);
table.setWidths(new int[]{12, 14, 15, 15, 15, 15, 14});
table.setTotalWidth(560);//设置绝对宽度
table.setLockedWidth(true);//使绝对宽度模式生效
PdfPCell cell11 = new PdfPCell(new Paragraph("列名1", FontChinese10Normal));
PdfPCell cell12 = new PdfPCell(new Paragraph("列名2", FontChinese10Normal));
PdfPCell cell13 = new PdfPCell(new Paragraph("列名3", FontChinese10Normal));
PdfPCell cell14 = new PdfPCell(new Paragraph("列名4", FontChinese10Normal));
PdfPCell cell15 = new PdfPCell(new Paragraph("列名5"