首先准备模板:
1.用Adobe Acrobat DC软件打开你的pdf模板文件点击准备表单;
2.编辑表单的属性和格式
3.最后点击保存,然后把模板文件放到resources文件夹下
4.再pom.xml文件中引入iTextPdf的依赖
com.itextpdf
itextpdf
5.4.3
com.itextpdf
itext-asian
5.2.0
5.创建一个工具类PdfUtils,用下面的方法来根据模板生成pdf文件 ,传入包含模板中所有表单属性的Map和模板文件的路径即可生成pdf文件
/**
* 根据模板创建生成pdf
* @param map 模板中的表单数据 key-表单属性值;value-值
* @param templatePath 模板路径
* @return 返回生成的pdf文件路径
*/
public static String createPdfByTemplate(Map map,String templatePath) {
PdfReader reader;
ByteArrayOutputStream bos;
PdfStamper stamper;
//生成的pdf文件存放地址 要确保文件夹的存在
String newPdfPath = "src/main/resources/static/temporary/"+(System.currentTimeMillis())+".pdf";
try {
//设置字体是必须要的,不然没法向模板pdf里写值
BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
// 读取pdf模板
reader = new PdfReader(templatePath);
bos = new ByteArrayOutputStream();
stamper = new PdfStamper(reader, bos);
//拿到pdf模板中的表单属性
AcroFields form = stamper.getAcroFields();
//设置字体
form.addSubstitutionFont(bfChinese);
java.util.Iterator it = form.getFields().keySet().iterator();
//遍历表单属性,对每个属性赋值
while (it.hasNext()) {
String name = it.next().toString();
String value = map.get(name)!=null?map.get(name).toString():null;
System.out.println(name+"------"+value);
form.setField(name,value);
}
// 如果为false那么生成的PDF文件还能编辑,一定要设为true
stamper.setFormFlattening(true);
stamper.close();
Document doc = new Document();
File file = new File(newPdfPath);
PdfCopy copy = new PdfCopy(doc, new FileOutputStream(file));
doc.open();
PdfImportedPage importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), 1);
copy.addPage(importPage);
doc.close();
} catch (IOException e) {
throw new BaseException("生成电子协议失败,请联系管理员");
} catch (DocumentException e) {
throw new BaseException("生成电子协议失败,请联系管理员");
}
return newPdfPath;
}
6.试例:
//生成电子协议
Map tAgreementApplyMap =ConvertUtils.transBean2Map(tAgreementApplyElecDTO);
String tAgreementElecPath = PdfUtils.createPdfByTemplate(tAgreementApplyMap,"src/main/resources/static/模板.pdf");