How to insert image programmatically in to AcroForm field using java PDFBox?

后端 未结 2 2151
情深已故
情深已故 2021-01-06 02:19

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

2条回答
  •  孤独总比滥情好
    2021-01-06 02:42

    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:

    • My field was made exactly square to fit QR codes which are always square
    • My images are black and white. I did not attempt to insert a color image
    • My template is known to have only one page, hence "document.getPage(0)"
    • I did not insert any text in the field used to position the image

    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);
    }
    

提交回复
热议问题