【发布时间】:2015-05-06 21:12:42
【问题描述】:
为了收集一些数据,我们有一个包含一些字段的 PDF,我必须通过在这些位置添加一些文本来以编程方式在 Android 上使用 iText 填充它。我一直在考虑不同的方法来实现这一目标,但每一种都收效甚微。
注意:我使用 Android 版本的 iText (iTextG 5.5.4) 和三星 Galaxy Note 10.1 2014 (Android 4.4) 进行大部分测试。
-
我从一开始就采用的方法是在给定坐标上为给定页面“绘制”文本。这对字段的管理有一些问题(我必须知道字符串的长度,并且可能很难将每个文本定位在 pdf 的确切坐标中)。但最重要的是,该过程的性能在某些设备/OSVersions 中确实很慢(它在 Nexus 5 和 5.0.2 中运行良好,但在 Note 10.1 上使用 5MB Pdf 需要几分钟)。
pdfReader = new PdfReader(is); document = new Document(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); pdfCopy = new PdfCopy(document, baos); document.open(); PdfImportedPage page; PdfCopy.PageStamp stamp; for (int i = 1; i <= pdfReader.getNumberOfPages(); i++) { page = pdfCopy.getImportedPage(pdfReader, i); // First page = 1 stamp = pdfCopy.createPageStamp(page); for (int i=0; i<10; i++) { int posX = i*50; int posY = i*100; Phrase phrase = new Phrase("Example text", FontFactory.getFont(FontFactory.HELVETICA, 12, BaseColor.RED)); ColumnText.showTextAligned(stamp.getOverContent(), Element.ALIGN_CENTER, phrase, posX, posY, 0); } stamp.alterContents(); pdfCopy.addPage(page); } 我们考虑添加“表单域”而不是绘图。这样我就可以配置一个 TextField 并避免自己管理文本。但是,最终的 PDF 不应该有任何注释,所以我需要将它复制到没有注释的新 Pdf 中,并绘制那些“表单域”。我没有这方面的例子,因为我无法执行此操作,我什至不知道这是否可能/值得。
第三个选项是接收已添加“表单域”的 Pdf,这样我只需填写它们。但是我仍然需要创建一个包含所有这些字段且没有注释的新 Pdf...
我想知道执行此过程的最佳性能方法是什么,以及实现它的任何帮助。我真的是 iText 的新手,任何帮助都将不胜感激。
谢谢!
编辑
最后,我使用了第三个选项:一个带有可编辑字段的 PDF,然后我们使用“拼合”创建一个不可编辑的 PDF,其中所有文本都已经存在。
代码如下:
pdfReader = new PdfReader(is);
FileOutputStream fios = new FileOutputStream(outPdf);
PdfStamper pdfStamper = new PdfStamper(pdfReader, fios);
//Filling the PDF (It's totally necessary that the PDF has Form fields)
fillPDF(pdfStamper);
//Setting the PDF to uneditable format
pdfStamper.setFormFlattening(true);
pdfStamper.close();
及填表方法:
public static void fillPDF(PdfStamper stamper) throws IOException, DocumentException{
//Getting the Form fields from the PDF
AcroFields form = stamper.getAcroFields();
Set<String> fields = form.getFields().keySet();
for(String field : fields){
form.setField("name", "Ernesto");
form.setField("surname", "Lage");
}
}
}
这种方法唯一的问题是您需要知道每个字段的名称才能填写它。
【问题讨论】: