我在尝试使用 Apache PDFBOX(1.8.5) 设置一些字段时遇到问题。我有几个不同的静态 PDF 用于测试。使用以下代码,我可以设置表单字段的值,并保存生成的 PDF。然后我可以在 Adobe Reader 中打开此 PDF 并查看结果:
PDDocumentCatalog docCatalog = pdfDocument.getDocumentCatalog();
pdfTemplate.setAllSecurityToBeRemoved(true);
PDAcroForm acroForm = docCatalog.getAcroForm();
List fields = acroForm.getFields();
Iterator fieldsIter = fields.iterator();
while( fieldsIter.hasNext())
{
PDField field = (PDField)fieldsIter.next();
if(field instanceof PDTextbox){
((PDTextbox)field).setValue("STATIC PDFBOX EDIT");
}
}
然后我最终保存了表格。对于静态 PDF:
- PDF 版本:1.6 (Acrobat 7.x)
- PDF 版本:1.7 (Acrobat 8.x)
这很好用。我可以在 Adobe Reader XI 中打开文档并在表单中看到正确的值。
对于以下的静态 PDF:
- PDF 版本:1.7 Adobe Extension Level 3(Acrobat 9.x)
- PDF 版本:1.7 Adobe Extension Level 8(Acrobat X)
- PDF 版本:1.7 Adobe Extension Level 11(Acrobat XI)
这似乎不起作用。当我在 Adobe Reader XI 中打开生成的表单时,这些字段似乎没有被填充。但是,如果我在 Firefox 或 Chrome 浏览器的 PDF 查看器中打开 PDF,字段会显示为已填充。
如何设置这些字段,以便在 Adobe Reader XI 中查看时显示值?
编辑:示例 PDF 可在此处找到:https://github.com/bamundson/PDFExample
最佳答案
PDF 之间的主要区别在于所使用的表单技术:
Test_9.pdf
使用很好的老式 AcroForm 表单;
另一方面,Test_10.pdf
和Test_10.pdf
使用混合形式,同时包含 AcroForm 表示和 XFA (Adobe XML 表单架构)表示。
支持 XFA 的 PDF 查看器(即最重要的 Adobe Reader 和 Adobe Acrobat)使用文件中的 XFA 信息,而不支持 XFA 的查看器(即大多数其他)使用 AcroForm 信息。
PDFBox 大部分是 XFA 未知的。这尤其意味着 PDACroForm.getFields()
返回的 PDField
对象仅代表 AcroForm 信息。因此,您的 ((PDTextbox)field).setValue("STATIC PDFBOX EDIT")
调用只会影响表单的 AcroForm 表示。
这解释了你的观察
When I open the resulting forms in Adobe Reader XI, the fields do not appear to be populated. But If I open the PDF in my Firefox or Chrome browser's PDF viewer, the fields show as populated there.
(据我所知,Firefox 和 Chrome 集成的 PDF 查看器无法识别 XFA。)
所以,
How can I set these fields so the values will appear when viewed in Adobe Reader XI?
基本上有两种方式:
从 AcroForm 字典中删除 XFA 条目:
acroForm.setXFA(null);
如果没有XFA,Adobe Reader 也会使用AcroForm 表单信息。
同时编辑 AcroForm 和 XFA 信息。您可以使用
检索 XFA 信息PDXFAResource xr = acroForm.getXFA();
并使用
提取底层 XMLxr.getDocument()
然后您可以编辑 XML,将生成的 XML 放入一个流中,您可以将其包装在
PDXFAResource
中,然后您可以使用AcroForm.setXFA(...)
.
虽然选项 1 确实更容易实现,但它仅适用于混合文档。如果您还必须编辑纯 XFA 表单,则需要实现选项 2。
Writing new field values to these PDFs works fine with the latest version of iText
iText 对 XFA 表单有一定程度的明确支持。
关于java - 使用 PDFBOX 设置的表单字段值在 Adobe Reader 中不可见,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24149361/