如何使用java PDFBox以编程方式将图像插入到AcroForm字段中?
我创建了带有3个标签的简单PDF文档:名字,姓氏和照片 . 然后我使用Adobe Acrobat PRO DC添加了带有2个“文本字段”的AcroForm图层和一个“图像字段” .
因此,如果我想填写表单,我可以在常规Acrobat Reader中打开此PDF文件,并通过键入名字,姓氏填写并插入照片我单击图像占位符并在打开的对话窗口中选择照片 .
但是我怎么能以编程方式做同样的事情呢?创建了简单的Java应用程序,它使用Apache PDFBox库(版本2.0.7)来查找表单字段和插入值 .
我可以轻松填充文本编辑字段,但无法弄清楚如何插入图像:
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中它说我添加了Image Field,但是我生成的名字只能获得的字段:'photo_af_image'是按钮类型 - PDPushButton (这就是为什么我检查是否(字段instanceof PDPushButton)),但与Image无关 .
How can I insert image to AcroForm 'photo_af_image' field, so that it will fit the size of a box created af Acrobat Pro DC?
2 years ago
我终于找到并 Build 了很好的解决方案 . 该解决方案的目标是:
使用简单的工具创建带有文本和图像占位符的表单层,这可以由非程序员完成,而不需要操作低级PDF结构;
使插入图像的大小由表单创建者使用简单工具驱动;尺寸由高度驱动,但宽度将按比例调整;
以下解决方案的主要思想是通过acroForm占位符插入图像:
你必须迭代acroForm层并找到带有相应占位符名称的按钮;
如果找到的字段是PDPushButton类型的第一个小部件;
从图像文件创建PDImageXObject;
使用PDImageXObject创建PDAppearanceStream并设置相同的x和y位置,并调整高度和宽度以匹配占位符的高度;
将此PDAppearanceStream设置为小部件;
您可以选择展平文档以将acroform lay合并到主文件中
这是代码:
如果有更好的解决方案,或者您可以改进此代码,请告诉我 .