I have created simple PDF document with 3 labels: First Name, Last Name and Photo. Then I added AcroForm layer with 2 \'Text Fields\' and one \'Image Field\' using Adobe Acr
The answer by Renat Gatin was invaluable for getting me started on this. Thank you for that. However, I found I could accomplish the same result with less complexity. The original answer seems to be using the PDPushButton field primarily to determine the field's size and location. The field itself has little to do with inserting the image. The code is writing directly to the document stream and not really populating the field.
I created a text field in my form which covers the entire area where I want the image, in my case a QR code. Then using the discovered coordinates of the field, I can write the image in the document. This was done using PDFBox 2.0.11.
Disclaimers:
Here is my partial code provided as an example, not a complete or generic solution:
public void setField(PDDocument document, String name, PDImageXObject image)
throws IOException {
PDAcroForm acroForm = document.getDocumentCatalog().getAcroForm();
PDField field = acroForm.getField(name);
if (field != null) {
PDRectangle rectangle = getFieldArea(field);
float size = rectangle.getHeight();
float x = rectangle.getLowerLeftX();
float y = rectangle.getLowerLeftY();
try (PDPageContentStream contentStream = new PDPageContentStream(document,
document.getPage(0), PDPageContentStream.AppendMode.APPEND, true)) {
contentStream.drawImage(image, x, y, size, size);
}
}
}
private PDRectangle getFieldArea(PDField field) {
COSDictionary fieldDict = field.getCOSObject();
COSArray fieldAreaArray = (COSArray) fieldDict.getDictionaryObject(COSName.RECT);
return new PDRectangle(fieldAreaArray);
}