And*_*rew 7 java pdf pdf-form pdfbox
我有一个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
Run Code Online (Sandbox Code Playgroud)
mkl*_*mkl 10
您的代码中有两个主要问题:
PDF的AcroForm元素是文档级对象.您只能将填写的模板页面复制到finalDoc.因此,表单字段finalDoc仅作为其各自页面的注释添加,但它们不会添加到AcroForm中finalDoc.
这在Adobe 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"));
}
Run Code Online (Sandbox Code Playgroud)
如您所见,所有字段在添加到finalForm以下内容之前都已重命名:
field.setPartialName("SampleField" + i++);
Run Code Online (Sandbox Code Playgroud)
它们被收集在fields最终添加到finalFormAcroForm 的列表中:
fields.add(field);
}
...
finalForm.setFields(fields);
Run Code Online (Sandbox Code Playgroud)