-
使用Adobe Acrobat Pro DC工具, 在准备表单模式下,先设置好表单域
引入iText依赖, 目前iText5版本较为稳定
<!-- Adobe iText 5 -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>1.49</version>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcpkix-jdk15on</artifactId>
<version>1.49</version>
</dependency>
<!-- // Adobe iText 5 -->
- 代码开发片段
......
PdfReader reader = null;
PdfStamper stamper;
ByteArrayOutputStream bos = null;
try {
reader = new PdfReader("模板文件路径");
bos = new ByteArrayOutputStream();
stamper = new PdfStamper(reader, bos);
AcroFields form = stamper.getAcroFields();
# templateInfo.getDataMap(), 根据表单字段传入数据集(K-V)
for (String fieldName : form.getFields().keySet()) {
form.setField(fieldName, templateInfo.getDataMap().get(fieldName));
}
stamper.setFormFlattening(true);
stamper.close();
Document newDocument = new Document();
PdfCopy copy = new PdfCopy(newDocument, outputStream);
# 允许浏览, 不可编辑
copy.setEncryption(null, null, PdfWriter.ALLOW_SCREENREADERS ,PdfWriter.ENCRYPTION_AES_128);
# 允许打印
copy.setEncryption(null, null, PdfWriter.ALLOW_PRINTING ,PdfWriter.ENCRYPTION_AES_128);
newDocument.open();
int pageSize = reader.getNumberOfPages();
for(int cur = 0; cur < pageSize; cur ++) {
copy.addPage(copy.getImportedPage(new PdfReader(bos.toByteArray()), cur + 1));
}
newDocument.close();
} catch (Exception e) {
logger.error("PDF build error, caused by ", e);
throw new PDFBuilderException("PDF build error.");
} finally {
if(reader != null) {
reader.close();
}
try {
if (bos != null) {
bos.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}