iText编辑Pdf模板



本文讲述JAVA如何操作PDF模板生成PDF文件。


1.由Word 文档生成PDF模板
工具:Microsoft Office Word , AdobeAcrobat_2015.exe(安装好后是 Adobe Acrobat DC 程序)
根据已有的word文档,用Adobe Acrobat DC通过调用word文档创建表单,Adobe Acrobat DC
会自动向word文档中的填写项生成文本域表单。这些表单就是要生成的PDF模板中要改变的值,
不够的地方可动态添加文本域表单。将带文本域表单的文件保存为PDF模板。


2.在JAVA程序中用iText读取、编辑PDF模板
工具包:itextpdf-5.4.3.jar , itext-asian-5.2.0.jar . 
Maven中的配置如下:
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.4.3</version>
</dependency>
<dependency>
   <groupId>com.itextpdf</groupId>
   <artifactId>itext-asian</artifactId>
   <version>5.2.0</version>
</dependency>
主要程序代码:
public void editPdfTemplate(String templateFile, String outFile)
throws IOException, DocumentException {
PdfReader reader = new PdfReader(templateFile); // 模版文件目录
PdfStamper ps = new PdfStamper(reader, new FileOutputStream(outFile)); // 生成的输出流
BaseFont bf = BaseFont.createFont("STSong-Light","UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);
AcroFields s =  ps.getAcroFields();
//设置文本域表单的字体
// 对于模板要显中文的,在此处设置字体比在pdf模板中设置表单字体的好处:
//1.模板文件的大小不变;2.字体格式满足中文要求
s.setFieldProperty("fill_3","textfont",bf,null);
s.setFieldProperty("fill_5","textfont",bf,null);
s.setFieldProperty("fill_2","textfont",bf,null);
s.setFieldProperty("fill_4","textfont",bf,null);
s.setFieldProperty("fill_6","textfont",bf,null);
//编辑文本域表单的内容
s.setField("fill_3", "姚 秀 才");
s.setField("fill_5", "cf");
s.setField("fill_2", "cn-990000");
s.setField("fill_4",  "模版文件目录");
s.setField("fill_6", "模版文件目录");
ps.setFormFlattening(true); // 这句不能少
ps.close();
reader.close();
}

猜你喜欢

转载自blog.csdn.net/xiucaiyao/article/details/45499583