Java-pdf模板制作流程-使用pdf 模板生成pdf文件

来源:互联网 发布:软件前端开发是什么 编辑:程序博客网 时间:2024/06/06 04:24

Java 使用pdf 模板生成pdf文件

——制作流程

1.      使用工具

adobe acrobat dc、word 2015

2.      使用 word 绘制一个 3*5 的表格并保存,如下:



3.      将文档另存为pdf格式

注:不要使用“另存为adobe pdf ”选项,这样保存出来的文档比较大(安装 adobe acrobat dc 工具后,word中会有该选项)


4.      打开已安装的adobe acrobat DC 工具

 

5.      文件->创建->创建表单,制作 pdf 模板


6.      选择要刚刚保存的pdf文件


7.      打开后,工具自动生成“文本域”


8.      修改文本域属性名


9.      修改文本域默认字体(选个 adobe 开头的字体,有助于程序生成)


10.  保存pdf模板


11.  多行文本域,可以设置自动换行


12.  以下为使用IText7通过 pdf 模板生成pdf 的效果


13.  文本域默认字体对文件大小有影响


改变前


改变后


14.  使用itext7 ,通过pdf模板生成pdf的主要代码

 
/** * 使用pdf 模板生成 pdf 文件 *  * @author xxj 2017年5月24日 */@Testpublic void fillTemplate() {// 利用模板生成pdf// 模板路径String templatePath = "D:/Temp/pdf/pdf-template-form.pdf";// 生成的新文件路径String fileName = StringExtend.format("itext-template-{0}.pdf", DateExtend.getDate("yyyyMMddHHmmss"));String newPDFPath = PathExtend.Combine("D:/Temp/pdf/", fileName);try {// com.lowagie.text.pdf.PdfStamper.PdfStamper// Initialize PDF documentPdfDocument pdf = new PdfDocument(new PdfReader(templatePath), new PdfWriter(newPDFPath));PdfAcroForm form = PdfAcroForm.getAcroForm(pdf, true);Map<String, PdfFormField> fields = form.getFormFields();String maxTxt = "你好,世界!hello word!你好,世界!hello word!你好,世界!hello word!"+ "你好,世界!hello word!你好,世界!hello word!你好,世界!hello word!"+ "你好,世界!hello word!你好,世界!hello word!你好,世界!hello word!"+ "你好,世界!hello word!你好,世界!hello word!你好,世界!hello word!"+ "你好,世界!hello word!你好,世界!hello word!你好,世界!hello word!"+ "你好,世界!hello word!你好,世界!hello word!你好,世界!hello word!";// 处理中文问题PdfFont font = PdfFontFactory.createFont("STSongStd-Light", "UniGB-UCS2-H", false);String[] str = { "01.hello word!", "02.你好,世界!", "03.hello word!", "04.你好,世界!", "05.hello word!","06.你好,世界!", "07.hello word!", "08.你好,世界!", "09.hello word!", "10.你好,世界!", "11.hello word!","12.你好,世界!", "13." + maxTxt, "14." + maxTxt, };int i = 0;java.util.Iterator<String> it = fields.keySet().iterator();while (it.hasNext()) {// 获取文本域名称String name = it.next().toString();// 填充文本域fields.get(name).setValue(str[i++]).setFont(font).setFontSize(12);System.out.println(name);}form.flattenFields();// 设置表单域不可编辑pdf.close();System.out.println("模板:" + templatePath);System.out.println("pdf:" + newPDFPath);} catch (IOException e) {e.printStackTrace();} catch (Exception e) {e.printStackTrace();}}


15.  常见问题


异常描述

java.lang.NullPointerException

         atcom.itextpdf.kernel.pdf.PdfDocument.getFont(PdfDocument.java:1479)

         atcom.itextpdf.forms.fields.PdfFormField.getFontAndSize(PdfFormField.java:2442)

         atcom.itextpdf.forms.fields.PdfFormField.regenerateField(PdfFormField.java:1780)

         atcom.itextpdf.forms.fields.PdfFormField.setValue(PdfFormField.java:1038)

         atcom.itextpdf.forms.fields.PdfFormField.setValue(PdfFormField.java:999)

解决方案:

打开pdf模板,将字体修改为 adobe 开头的字体,如 adobe pi

原创粉丝点击