首页 文章

iText Android - 将文本添加到现有 PDF

提问于
浏览
5

我们有一些带有一些字段的 PDF 来收集一些数据,我必须在 Android 上通过在这些位置添加一些文本以 iText 编程方式填写它。我一直在考虑实现这一目标的不同方法,但每个方法都没有成功。

注意:我的大多数测试都使用 Android 版 iText(iTextG 5.5.4)和三星 Galaxy Note 10.1 2014(Android 4.4)。

  • 我从一开始就采用的方法是在给定页面上“绘制”给定坐标上的文本。这对字段的管理有一些问题(我必须知道字符串的长度,并且很难将每个文本放在 pdf 的精确坐标中)。但最重要的是,在某些 devices/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 中,并绘制那些“表单字段”。我没有这样的例子,因为我无法执行此操作,我甚至不知道这是否是 possible/worthwhile。

  • 第三种选择是接收已添加“表单字段”的 Pdf,这样我只需填写它们。但是我仍然需要创建一个包含所有这些字段且没有注释的新 Pdf ...

我想知道执行此过程的最佳性能方式,以及实现它的任何帮助。我是 iText 的新手,任何帮助都会非常感激。

谢谢!

编辑

最后,我使用了第三个选项:带有可编辑字段的 PDF,然后我们使用“展平”创建一个包含所有文本的 non-editable 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");
        }
    }
}

这种方法的唯一之处在于您需要知道每个字段的名称才能填充它。

1 回答

  • 4

    iText 中有一个称为“展平”的过程,它接受表单字段,并用字段包含的文本替换它们。

    我没有在几年内使用 iText(在 Android 上也没有使用过),但是如果您在手册或在线示例中搜索“展平”,您应该找到如何做到这一点。

相关问题