我已经创建了3个标签的简单PDF文档:名字,姓氏和照片。然后,我使用Adobe Acrobat PRO DC将2个“文本字段”和一个“图像字段”添加到AcroForm图层。如何使用java PDFBox以编程方式将图像插入AcroForm字段?
所以,如果我要填写我可以在常规的Acrobat Reader中打开该PDF文件,并通过键入名字,姓氏填满,以便插入图片的形式我点击图像占位符和在打开的对话窗口中选择照片。
但我怎么能做到同样的事情编程? 创建使用Apache PDFBox库(版本2.0.7)来查找表单域并插入值的简单Java应用程序。
我可以很容易地填充文本编辑字段,但无法弄清楚如何我可以插入图片:
public class AcroFormPopulator {
public static void main(String[] args) {
AcroFormPopulator abd = new AcroFormPopulator();
try {
abd.populateAndCopy("test.pdf", "generated.pdf");
} catch (IOException e) {
e.printStackTrace();
}
}
private void populateAndCopy(String originalPdf, String targetPdf) throws IOException {
File file = new File(originalPdf);
PDDocument document = PDDocument.load(file);
PDAcroForm acroForm = document.getDocumentCatalog().getAcroForm();
Map<String, String> data = new HashMap<>();
data.put("firstName", "Mike");
data.put("lastName", "Taylor");
data.put("photo_af_image", "photo.jpeg");
for (Map.Entry<String, String> item : data.entrySet()) {
PDField field = acroForm.getField(item.getKey());
if (field != null) {
if (field instanceof PDTextField) {
field.setValue(item.getValue());
} else if (field instanceof PDPushButton) {
File imageFile = new File(item.getValue());
PDPushButton pdPushButton = (PDPushButton) field;
// do not see way to isert image
} else {
System.err.println("No field found with name:" + item.getKey());
}
} else {
System.err.println("No field found with name:" + item.getKey());
}
}
document.save(targetPdf);
document.close();
System.out.println("Populated!");
}
}
我有杰出一个奇怪的事情 - 在Acrobat Pro的DC,它说,我添加图片的领域,但我得到的唯一字段是:'photo_af_image'是类型按钮 - PDPushButton(这就是为什么我检查是否(field instanceof PDPushButton)),但与Image无关。
如何将图像插入到AcroForm'photo_af_image'字段,以便它适合Acrobat Pro DC创建的盒子的尺寸?