我终于找到并建立了很好的解决方案。该解决方案的目标是:
- 使用简单的工具创建带有文本和图像占位符的表单层,这可以由非程序员完成,并且不需要操作低级 PDF 结构;
- 使用简单的工具使插入图像的大小由表单创建者驱动;大小由高度驱动,但宽度将按比例调整;
下面通过 acroForm 占位符插入图像的解决方案的主要思想是:
- 您必须迭代 acroForm 层并找到具有相应占位符名称的按钮;
- 如果找到的字段是 PDPushButton 类型,则获取其第一个小部件;
- 从图像文件创建 PDImageXObject;
- 使用 PDImageXObject 创建 PDAppearanceStream 并设置相同的 x & y 位置并调整高度和宽度以匹配占位符的高度;
- 将此 PDAppearanceStream 设置为小部件;
- 您可以选择展平文档以将 acroform 布局合并到主要的
这是代码:
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.imageio.ImageIO;
import org.apache.pdfbox.cos.COSArray;
import org.apache.pdfbox.cos.COSDictionary;
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.PDResources;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.graphics.image.LosslessFactory;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
import org.apache.pdfbox.pdmodel.interactive.action.PDAction;
import org.apache.pdfbox.pdmodel.interactive.action.PDActionHide;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationWidget;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAppearanceDictionary;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAppearanceStream;
import org.apache.pdfbox.pdmodel.interactive.form.PDAcroForm;
import org.apache.pdfbox.pdmodel.interactive.form.PDField;
import org.apache.pdfbox.pdmodel.interactive.form.PDPushButton;
import org.apache.pdfbox.pdmodel.interactive.form.PDTextField;
public class AcroFormPopulator {
public static void main(String[] args) {
AcroFormPopulator abd = new AcroFormPopulator();
try {
Map<String, String> data = new HashMap<>();
data.put("firstName", "Mike");
data.put("lastName", "Taylor");
data.put("dateTime", (new Date()).toString());
data.put("photo_af_image", "photo1.jpg");
data.put("photo2_af_image", "photo2.jpg");
data.put("photo3_af_image", "photo3.jpg");
abd.populateAndCopy("test.pdf", "generated.pdf", data);
} catch (IOException e) {
e.printStackTrace();
}
}
private void populateAndCopy(String originalPdf, String targetPdf, Map<String, String> data) throws IOException {
File file = new File(originalPdf);
PDDocument document = PDDocument.load(file);
PDAcroForm acroForm = document.getDocumentCatalog().getAcroForm();
for (Map.Entry<String, String> item : data.entrySet()) {
String key = item.getKey();
PDField field = acroForm.getField(key);
if (field != null) {
System.out.print("Form field with placeholder name: '" + key + "' found");
if (field instanceof PDTextField) {
System.out.println("(type: " + field.getClass().getSimpleName() + ")");
field.setValue(item.getValue());
System.out.println("value is set to: '" + item.getValue() + "'");
} else if (field instanceof PDPushButton) {
System.out.println("(type: " + field.getClass().getSimpleName() + ")");
PDPushButton pdPushButton = (PDPushButton) field;
List<PDAnnotationWidget> widgets = pdPushButton.getWidgets();
if (widgets != null && widgets.size() > 0) {
PDAnnotationWidget annotationWidget = widgets.get(0); // just need one widget
String filePath = item.getValue();
File imageFile = new File(filePath);
if (imageFile.exists()) {
/*
* BufferedImage bufferedImage = ImageIO.read(imageFile);
* PDImageXObject pdImageXObject = LosslessFactory.createFromImage(document, bufferedImage);
*/
PDImageXObject pdImageXObject = PDImageXObject.createFromFile(filePath, document);
float imageScaleRatio = (float) pdImageXObject.getHeight() / (float) pdImageXObject.getWidth();
PDRectangle buttonPosition = getFieldArea(pdPushButton);
float height = buttonPosition.getHeight();
float width = height / imageScaleRatio;
float x = buttonPosition.getLowerLeftX();
float y = buttonPosition.getLowerLeftY();
PDAppearanceStream pdAppearanceStream = new PDAppearanceStream(document);
pdAppearanceStream.setResources(new PDResources());
try (PDPageContentStream pdPageContentStream = new PDPageContentStream(document, pdAppearanceStream)) {
pdPageContentStream.drawImage(pdImageXObject, x, y, width, height);
}
pdAppearanceStream.setBBox(new PDRectangle(x, y, width, height));
PDAppearanceDictionary pdAppearanceDictionary = annotationWidget.getAppearance();
if (pdAppearanceDictionary == null) {
pdAppearanceDictionary = new PDAppearanceDictionary();
annotationWidget.setAppearance(pdAppearanceDictionary);
}
pdAppearanceDictionary.setNormalAppearance(pdAppearanceStream);
System.out.println("Image '" + filePath + "' inserted");
} else {
System.err.println("File " + filePath + " not found");
}
} else {
System.err.println("Missconfiguration of placeholder: '" + key + "' - no widgets(actions) found");
}
} else {
System.err.print("Unexpected form field type found with placeholder name: '" + key + "'");
}
} else {
System.err.println("No field found with name:" + key);
}
}
// you can optionally flatten the document to merge acroform lay to main one
acroForm.flatten();
document.save(targetPdf);
document.close();
System.out.println("Done");
}
private PDRectangle getFieldArea(PDField field) {
COSDictionary fieldDict = field.getCOSObject();
COSArray fieldAreaArray = (COSArray) fieldDict.getDictionaryObject(COSName.RECT);
return new PDRectangle(fieldAreaArray);
}
}
如果有更好的解决方案或您可以改进此代码,请告诉我。