Java pdfBox:填写pdf表单,将其附加到pddocument,然后重复

我有一个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

解决方法

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

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

这在Adobe Reader中并不明显,但表单填写服务通常会从文档级AcroForm条目中识别可用字段,而不会在页面搜索其他表单字段.
>实际显示停止:您向PDF添加具有相同名称的字段.但PDF表单是文档范围内的实体.即在PDF中只能有一个具有给定名称的字段实体. (此字段实体可能具有多个可视化,也称为小部件,但这需要您构建具有多个子小部件的单个字段对象.此外,这些小部件应显示相同的值,而不是您想要的…)

因此,在将字段添加到finalDoc之前,必须唯一地重命名字段.

这里有一个simplified example,它只能在一个只有一个字段“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++);

它们被收集在列表字段中,最终被添加到finalForm AcroForm中:

fields.add(field);
}
...
finalForm.setFields(fields);

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...