Java pdfBox: Fill out pdf form, append it to pddocument, and repeat

…衆ロ難τιáo~ 提交于 2019-11-30 13:51:29

There are two major issues in you code:

  • The AcroForm element of a PDF is a document level object. You only copy the filled-in template page into finalDoc. Thus, the form fields are added to finalDoc only as annotations of their respective page but they are not added to the AcroForm of finalDoc.

    This is not apparent in Adobe Reader but form filling services often identify available fields from the document level AcroForm entry and don't search the pages for additional form fields.

  • The actual show stopper: You add fields with identical names to the PDF. But PDF forms are document-wide entities. I.e. there can be only a single field entity with a given name in a PDF. (This field entity may have multiple visualizations aka widgets but this requires you to construct a single field object with multiple kid widgets.Furthermore these widgets are expected to display the same value which is not what you want...)

    Thus, you have to rename the fields uniquely before adding them to the finalDoc.

Here a simplified example which works on a template with only one field "SampleField":

byte[] template = generateSimpleTemplate();
Files.write(new File(RESULT_FOLDER,  "template.pdf").toPath(), template);

try (   PDDocument finalDoc = new PDDocument(); )
{
    List<PDField> fields = new ArrayList<PDField>();
    int i = 0;

    for (String value : new String[]{"eins", "zwei"})
    {
        PDDocument doc = new PDDocument().load(new ByteArrayInputStream(template));
        PDDocumentCatalog docCatalog = doc.getDocumentCatalog();
        PDAcroForm acroForm = docCatalog.getAcroForm();
        PDField field = acroForm.getField("SampleField");
        field.setValue(value);
        field.setPartialName("SampleField" + i++);
        List<PDPage> pages = docCatalog.getAllPages();
        finalDoc.addPage(pages.get(0));
        fields.add(field);
    }

    PDAcroForm finalForm = new PDAcroForm(finalDoc);
    finalDoc.getDocumentCatalog().setAcroForm(finalForm);
    finalForm.setFields(fields);

    finalDoc.save(new File(RESULT_FOLDER, "form-two-templates.pdf"));
}

As you see all fields are renamed before they are added to finalForm:

field.setPartialName("SampleField" + i++);

and they are collected in the list fields which finally is added to the finalForm AcroForm:

    fields.add(field);
}
...
finalForm.setFields(fields);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!