itext7将pdf模板转成pdf文件

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/forwujinwei/article/details/81989637

使用adobe Acrobat Pro DC制作pdf模板

这里就略了,大家可以上网搜下,有很多方法

撸代码

在itext7第一节的基础上在pom文件添加junit依赖方便测试

<dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
 </dependency>

写实现方法

@Test
    public void tranPdf() {
        // 模板地址
        String filePath = "/test.pdf";
        // 填完信息后生成新的模板地址
        String toPath = "E:\\test_1.pdf";
        try {
            System.out.println(filePath);
            PdfDocument pdfDoc = new PdfDocument(new PdfReader(filePath), new PdfWriter(toPath));
            PdfAcroForm pdfAcroForm = PdfAcroForm.getAcroForm(pdfDoc, true);

            Map<String, PdfFormField> formFields = pdfAcroForm.getFormFields();
            System.out.println(formFields.size());
            //设置字体,如果不设置报空指针异常
            PdfFont f2 = PdfFontFactory.createFont("STSong-Light", "UniGB-UCS2-H",true);
            PdfFormField agreementId = formFields.get("name");
            agreementId.setFont(f2);
            agreementId.setValue("wujinwei");
            //设置生成表单不可编辑,注意itext的版本,在7.0.0版本报错
            pdfAcroForm.flattenFields();
            pdfDoc.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

亲测有效

猜你喜欢

转载自blog.csdn.net/forwujinwei/article/details/81989637