8

我制作了一个 pdf 表格,我正在尝试使用 pdfBox 填写表格并打印文档。我让它适用于 1 页打印作业,但我不得不尝试修改多页。基本上它是一个顶部有基本信息和内容列表的表格。好吧,如果内容大于表单的空间,我必须将其设为多页文档。我最终得到一个带有漂亮第一页的文档,然后所有剩余的页面都是空白模板。我究竟做错了什么?

PDDocument finalDoc = new PDDocument();
File template = new File("path/to/template.pdf");

//Declare basic info to be put on every page
String name = "John Smith";
String phoneNum = "555-555-5555";
//Get list of contents for each page
List<List<Map<String, String>>> pageContents = methodThatReturnsMyInfo();

for (List<Map<String, String>> content : pageContents) {
    PDDocument doc = new PDDocument().load(template);
    PDDocumentCatlog docCatalog = doc.getDocumentCatalog();
    PDAcroForm acroForm = docCatalog.getAcroForm();

    acroForm.getField("name").setValue(name);
    acroForm.getField("phoneNum").setValue(phoneNum);

    for (int i=0; i<content.size(); i++) {
        acroForm.getField("qty"+i).setValue(content.get(i).get("qty"));
        acroForm.getField("desc"+i).setValue(content.get(i).get("desc"));
    }

    List<PDPage> pages = docCatalog.getAllPages();
    finalDoc.addPage(pages.get(0));
}

//Then prints/saves finalDoc
4

1 回答 1

13

您的代码中有两个主要问题:

  • PDF 的 AcroForm 元素是文档级对象。您只需将填写好的模板页面复制到finalDoc. 因此,表单字段finalDoc仅作为其各自页面的注释添加到,但不会添加到finalDoc.

    这在 Adob​​e Reader 中并不明显,但表单填写服务通常会从文档级别的 AcroForm 条目中识别可用字段,并且不会在页面中搜索其他表单字段。

  • 实际显示停止:您将具有相同名称的字段添加到 PDF。但 PDF 表单是文档范围的实体。即,PDF 中只能有一个具有给定名称的字段实体。(这个字段实体可能有多个可视化,也就是小部件,但这需要您使用多个孩子小部件构造单个字段对象。此外,这些小部件预计会显示相同的值,这不是您想要的......)

    因此,您必须在将字段添加到finalDoc.

这是一个简化的示例,它适用于只有一个字段“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"));
}

如您所见,所有字段在添加到之前都已重命名finalForm

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

并将它们收集在fields最终添加到finalFormAcroForm 的列表中:

    fields.add(field);
}
...
finalForm.setFields(fields);
于 2015-04-02T16:33:15.433 回答