Java-PDF的模板导出

2,626 阅读2分钟

简要说明

PDF其实包含了表单域,类似form表单,一个名字对应的一个表单,但需要特殊的工具处理才清楚这个表单

准备PDF模板

  • 用Word文档准备一个需要的模板
  • 导出为PDF
  • 重点来了,需要使用一个特殊的工具Adobe Acrobat DC,需要收费的,但可以免费使用30天
  • 用这个工具打开pdf文件,有一个准备表单的功能,点击一下就会显示表单
  • 灰色显示的就是表单,你可以修改key值,对应各个输入框,模板导出的时候就会填充对应的值
  • 修改表单后,保存,PDF的模板就生成了

PDF模板导出

  • 使用的是itextpdf工具类,引入依赖
<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.5.11</version>
</dependency>
  • 代码PdfUtil
public class GeneratePDFUtil {

    // 利用模板生成pdf
    public static void interviewReportPDF(Map<String, String> map) {
        // 模板路径
        String templatePath = "D:/ProhibitDelete/test1.pdf";
        // 生成的新文件路径
        String newPDFPath = "D:/ProhibitDelete/test1-data.pdf";
        PdfReader reader;
        FileOutputStream out;
        ByteArrayOutputStream bos;
        PdfStamper stamper;
        try {
            // 输出流
            out = new FileOutputStream(newPDFPath);
            // 读取pdf模板
            reader = new PdfReader(templatePath);
            bos = new ByteArrayOutputStream();
            stamper = new PdfStamper(reader, bos);
            AcroFields form = stamper.getAcroFields();

            // 给表单添加中文字体 这里采用系统字体。不设置的话,中文可能无法显示
            BaseFont bf = BaseFont.createFont("C:/Windows/Fonts/simfang.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            form.addSubstitutionFont(bf);

            //遍历map装入数据
            for (Entry<String, String> entry : map.entrySet()) {
                form.setField(entry.getKey(), entry.getValue());
                System.out.println("插入PDF数据---->  key= " + entry.getKey() + " and value= " + entry.getValue());
            }

            // 如果为false那么生成的PDF文件还能编辑,一定要设为true
            stamper.setFormFlattening(true);
            stamper.close();

            Document doc = new Document();
            PdfCopy copy = new PdfCopy(doc, out);
            doc.open();
            // 这里是PDF的页数 如果有两页及以上,还需要构造PdfImportedPage
            PdfImportedPage importPage1 = copy.getImportedPage(new PdfReader(bos.toByteArray()), 1);
            copy.addPage(importPage1);
            doc.close();
        } catch (DocumentException | IOException e) {
            e.printStackTrace();
        }
    }

    // 测试
    public static void main(String[] args) {
        Map<String, String> m = new HashMap<>();
        m.put("name", "冯杰");
        m.put("age", "23");
        m.put("sex", "男");
        m.put("deptName", "能力建设中心");
        interviewReportPDF(m);
    }
}
  • 导出的PDF就会填充数据

源码:github.com/solitary-s/…