I created a sample PDF form with one image field. I'm trying to set an image to the field using PDFBox.
I see that PDFBox treats such field as an instance of PDPushButton
but I don't see this class' interface exposes methods to deal with images...
The sample PDF can be downloaded using the URL in comment.
How can it be done?
EDIT:
Here is what I'm doing so far:
PDDocument pdfDocument = null;
PDAcroForm acroForm = pdfDocument.getDocumentCatalog().getAcroForm();
if (acroForm != null) {
PDPushButton field = (PDPushButton) acroForm.getField("test");
PDImageXObject pdImageXObject = PDImageXObject.createFromFile("my_img.png", pdfDocument);
List<PDAnnotationWidget> widgets = field.getWidgets();
/*
* The field may appear multiple times in the document, I would like to repeat that for every widget (occurence).
*/
for(PDAnnotationWidget widget : widgets) {
PDRectangle rectangle = widget.getRectangle();
//PDAppearanceDictionary appearanceDict = widget.getAppearance();
/*
* In my case, when the image is not set with Acrobat DC, appearanceDict is null.
*/
/*
* Create the appearance stream and fill it with the image.
*/
PDAppearanceStream pdAppearanceStream = new PDAppearanceStream(pdfDocument);
pdAppearanceStream.setResources(new PDResources());
try (PDPageContentStream pdPageContentStream = new PDPageContentStream(pdfDocument, pdAppearanceStream)) {
pdPageContentStream.drawImage(pdImageXObject, rectangle.getLowerLeftX(), rectangle.getLowerLeftY(), pdImageXObject.getWidth(), pdImageXObject.getHeight());
}
pdAppearanceStream.setBBox(new PDRectangle(rectangle.getWidth(), rectangle.getHeight()));
/*
* Create the appearance dict with only one appearance (default) and set the appearance to the widget.
*/
PDAppearanceDictionary appearanceDict = new PDAppearanceDictionary();
appearanceDict.setNormalAppearance(pdAppearanceStream);
widget.setAppearance(appearanceDict);
}
}
ByteArrayOutputStream outStr = new ByteArrayOutputStream();
pdfDocument.save(outStr);
pdfDocument.close();
However, the generated PDF doesn't show any image with Acrobat Reader.
My goal is to start with this PDF and use PDFBox to get this PDF.