itext7將pdf模板轉成pdf檔案
阿新 • • 發佈:2018-11-20
使用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();
}
}
親測有效