前言
最近做项目有个功能需要跟据pdf模板然后填充数据导出,所以就研究了下。
准备工作
- 1.准备包
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.10</version>
</dependency>
- 2.制作模板
1.使用word做好模板另存为pdf
2.使用AdobeAcrobat打开pdf文档
3.设计表单
这一步导入后它会自动识别哪些是表单项
双击表单项可以编辑,设置字体,多行,以及表单名等等。
编码
记得把模板放入程序中,我是放在resourse目录下
1.根据模板填充数据
/**
* 根据pdf模板输出流
* @param templateFilePath
* @param templateFileName
* @param resultMap
* @return
*/
public static ByteArrayOutputStream createPdfStream(String templateFilePath, String templateFileName,
Map<String, String> resultMap) {
ByteArrayOutputStream ba = new ByteArrayOutputStream();
try {
PdfReader reader = new PdfReader(templateFilePath + "\\" + templateFileName);
PdfStamper stamp = new PdfStamper(reader, ba);
//使用字体
BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
/* 获取模版中的字段 */
AcroFields form = stamp.getAcroFields();
//填充表单
if (resultMap != null) {
for (Map.Entry<String, String> entry : resultMap.entrySet()) {
form.setFieldProperty(entry.getKey(), "textfont", bf, null);
form.setField(entry.getKey(), entry.getValue());
}
}
stamp.setFormFlattening(true);//不能编辑
stamp.close();
reader.close();
} catch (IOException ioException) {
ioException.printStackTrace();
} catch (DocumentException documentException) {
documentException.printStackTrace();
}
return ba;
}
2.导出方法
//1.准备数据源
Map<String, String> resultMap=new HashMap<>();
resultMap.put("name","张三");
resultMap.put("idCard","123456789123456789");
//2.根据模板填充数据源
ByteArrayOutputStream pdf = createPdfStream(ClassLoader.getSystemResource("pdf").getPath(), "测试.pdf", resultMap);
//3.输出填充后的文件
String newPadPath="E:\\com.Janhe\\SpringBoot_v2\\src\\main\\resources\\pdf"+"\\11.pdf";
FileOutputStream out = new FileOutputStream(newPadPath);
out.write(pdf.toByteArray());
out.flush();
out.close();
pdf.close();
之后去地址查看是否有这个文件就OK了。
本篇首发于橙寂博客转载请加上此标示。