注意:我使用的是iText的Android版本(iTextG 5.5.4),并且大多数测试是在三星Galaxy Note 10.1 2014(Android 4.4)上进行的。
The approach I took from the start was to "draw" the text on a given coordinates, for a given page. This has some problems with the management of the fields (I have to be aware of the length of the strings, and it could be hard to position each text in the exact coordinate of the pdf). But most importantly, the performance of the process is really slow in some devices/OSVersions (it works great in Nexus 5 with 5.0.2, but takes several minutes with a 5MB Pdf on the Note 10.1).
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); }
We though about adding "forms fields" instead of drawing. That way I can configure a TextField and avoid managing the texts myself. However, the final PDF shouldn't have any annotations, so I would need to copy it into a new Pdf without annotations and with those "forms fields" drawn. I don't have an example of this because I wasn't able to perform this, I don't even know if this is possible/worthwhile.
The third option would be to receive a Pdf with the "forms fields" already added, that way I only have to fill them. However I still need to create a new Pdf with all those fields and without annotations...
谢谢!
编辑
最终我使用了第三种选择:具有可编辑字段的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");
}
}
}
这种方法的唯一缺点是您需要知道每个字段的名称才能填写它。