文章目录
前言
如何利用PDF模版填充数据,生成我们想要的PDF文件呢?
一、准备好PDF模版
1、注备好需要生成的PDF文件
2、使用编辑器(例如:福昕高级PDF编辑器)编辑PDF文件,新建文本域,并保存。
二、代码示例
1.依赖
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.9</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
2.代码
/**
* 利用模板生成pdf,入参为设置的文本域替换字段
*/
@Override
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public void pdfOut(Map<String, String> inputMap) throws Exception {
// 模板路径
File directory = new File("");// 参数为空
String templatePath = directory.getCanonicalPath() + File.separator + "file/contractPDF.pdf";
// 输出文件夹(临时)
String newPdfPath = directory.getCanonicalPath() + File.separator + "fileout";
if(!new File(newPdfPath).exists()){
new File(newPdfPath).mkdir();
}
//字体文件
String simfangPath = directory.getCanonicalPath() + File.separator + "file/simfang.ttf";
PdfReader reader;
FileOutputStream out;
ByteArrayOutputStream bos;
PdfStamper stamper;
try {
BaseFont bf = BaseFont.createFont(simfangPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
// 输出流
String fileName = UUID.randomUUID().toString().replace("-","") + ".pdf";
String filePath = newPdfPath + File.separator + fileName;
File outFile = new File(filePath);
if (!outFile.getParentFile().exists()) {
outFile.getParentFile().mkdirs();
}
out = new FileOutputStream(filePath);
// 读取pdf模板
reader = new PdfReader(templatePath);
bos = new ByteArrayOutputStream();
stamper = new PdfStamper(reader, bos);
AcroFields form = stamper.getAcroFields();
//文字类的内容处理
Map<String, String> datemap = inputMap;
form.addSubstitutionFont(bf);
for (String key : datemap.keySet()) {
String value = datemap.get(key);
form.setField(key, value);
}
stamper.setFormFlattening(false);
stamper.close();
Document doc = new Document();
PdfCopy copy = new PdfCopy(doc, out);
doc.open();
for (int i = 1; i < 4; i++) {
PdfImportedPage importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), i);
copy.addPage(importPage);
}
doc.close();
//filePath 为得到的pdf文件
//上传阿里云,返回pdf路径
//保存阿里云返回的文件路径
//删除临时文件
File delFile = new File(filePath);
if(delFile.exists()){
delFile.delete();
}
} catch (Exception ex) {
throw new Exception(ex);
}
}
三、总结
该方法适用于数据固定的pdf文件生成。
如果模版数据pdf文件数据格式动态改变,比如有动态表格的情况下,可参考利用html模版生成PDF文件_奕安的博客-CSDN博客,使用html模版动态生成。