Java生成Pdf Itext插件: 解析PDF模板生成PDF表单
IText是用于生成PDF文档的一个java类库。
官方网站 :https://itextpdf.com/
(一)通过maven引入Itext 的jar包
<!-- 生成pdf --> <dependency> <groupId>com.itextpdf</groupId> <artifactId>itextpdf</artifactId> <version>5.4.3</version> </dependency>
(二)读取PDF即模板的使用
1、使用Adobe Acrobat 制作PDF模板(可以用word先编辑,另存为PDF格式)
a)文本域:工具-内容编辑-编辑文本域图像(自动会选中)
b)表单域:工具-表单-编辑-编辑-添加新域(或者编辑域)
c)编辑表单域可以设置一个name,
(三)实现代码
//申请信息表模板 private static String TEMPLATE_PDF_NAME="template.pdf"; //申请信息表模板 private static String APPLY_PDF_NAME="apply.pdf"; public String createPdfTest(List<LicApplyPersonEntity> personlist) { //生成申请信息表PDF try { String uploadPath = "E:/"; applicationPdf(licOrgApply, uploadPath); return "yes"; } catch (Exception e) { e.printStackTrace(); return "pdf处理失败,原因:"+e.getMessage(); } } /** * 生成信息表pdf */ public void applicationPdf(LicOrgApplyEntity licOrgApply,String uploadPath) throws IOException, DocumentException { Gson gson = new Gson(); String json = gson.toJson(licOrgApply); System.out.println(json); Map<?, ?> map = gson.fromJson(json, HashMap.class); //获取模板路径 //String PdfTemplateFile = "E:/"+TEMPLATE_PDF_NAME; //获取 resources 中 模板文件 URL PdfTemplateFile =Resources.getResource(TEMPLATE_PDF_NAME); // 生成的文件路径 String PdfResultFile = uploadPath+ APPLY_PDF_NAME; // 模板pdf //PdfReader pdfReader = new PdfReader(Global.getProperty("upload.path") + TEMPLATE_PDF_NAME); PdfReader pdfReader = new PdfReader(PdfTemplateFile); // 新pdf FileOutputStream fileOutputStream = new FileOutputStream(PdfResultFile); // 生成新的pdf PdfStamper pdfStamper = new PdfStamper(pdfReader, fileOutputStream); // 填充表单域 AcroFields acroFields = pdfStamper.getAcroFields(); // 显示中文字体 //URL FontURL= Resources.getResource("SIMFANG.TTF"); //BaseFont ChineseBaseFont = BaseFont.createFont( Resources.getResource("SIMFANG.TTF"), BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); BaseFont ChineseBaseFont = BaseFont.createFont( "c://windows//fonts//simkai.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); //Font ChineseFont = new Font(ChineseBaseFont, 14, Font.NORMAL); acroFields.addSubstitutionFont(ChineseBaseFont); // 循环使Map和表单域中字段对应 Map<String, Item> fieldmap = acroFields.getFields(); Set<Entry<String, Item>> set = fieldmap.entrySet(); Iterator<Entry<String, Item>> iterator = set.iterator(); while (iterator.hasNext()) { Entry<?, ?> entry = (Entry<?, ?>) iterator.next(); String key = (String) entry.getKey(); } } //模板中的变量赋值之后不能编辑 pdfStamper.setFormFlattening(true); //解析器关闭 pdfStamper.close(); //阅读器关闭 pdfReader.close(); }
参考博客:http://blog..net/u012228718/article/details/40706499