【发布时间】:2015-02-24 10:45:55
【问题描述】:
- 我有多个使用 acroforms 和 pdfbox 填充多条记录 (a.pdf,b.pdf,c[0-9].pdf,d[0-9].pdf,ez.pdf) 的 PDF。
- 生成的文件(aflat.pdf、bflat.pdf、c[0-9]flat.pdf、d[0-9]flat.pdf、ezflat.pdf)应该有它们的形式(字典和任何 adobe 使用的)已删除,但填充为原始文本的字段保存在 pdf 中(setReadOnly 不是我想要的!)。
PdfStamper 只能删除字段而不保存其内容,但我发现了一些对 PdfContentByte 的引用作为保存内容的一种方式。唉,文档太简短了,无法理解我应该如何做到这一点。
作为最后的手段,我可以使用FieldPosition 直接在 PDF 上书写。有没有人遇到过这样的问题?我该如何解决?
更新:保存单页 b.pdf 会生成有效的 bfilled.pdf,但会生成空白的 bflattened.pdf。保存整个文档解决了这个问题。
populateB();
try (PDDocument doc = new PDDocument(); FileOutputStream stream = new FileOutputStream("bfilled.pdf")) {
//importing the page will corrupt the fields
/*wrong approach*/doc.importPage((PDPage)pdfDocuments.get(0).getDocumentCatalog().getAllPages().get(0));
/*wrong approach*/doc.save(stream);
//save the whole document instead
pdfDocuments.get(0).save(stream);//<---right approach
}
try (FileOutputStream stream = new FileOutputStream("bflattened.pdf")) {
PdfStamper stamper = new PdfStamper(new PdfReader("bfilled.pdf"), stream);
stamper.setFormFlattening(true);
stamper.close();
}
【问题讨论】:
-
您说您的 PDF 文件是使用 acroforms 和 pdfbox 填充的。 PDFBox 是否为这些字段创建了外观流?如果没有,您可能想阅读布鲁诺的this answer。
-
文档说:设置生成外观的选项。不生成外观将加快表单填写,但在 Acrobat 中结果可能出乎意料。除非您的环境得到很好的控制,否则不要使用它。默认为真。