Using iText PdfStamper to insert Images in PDFs while preserving Acroforms

29 / Nov / 2010 by Vivek Krishna 2 comments

We had a requirement that a template PDF which had Acroform fields had to be pre-populated (like name, email id etc) and sent to the end user so that he/she only needed to fill in the details which were expected to be filled by him/her.

After going through the iText library, we found that the PdfStamper class was the best way to go about it. However, we also discovered that we needed to embed a data matrix image in the document so that it can be identified by scanning the printed version of the document which is received back from the end user. After pondering on how to do it, we stumbled across this page. This was the perfect solution we were looking for.

Our service method looked something like

def populateFieldsAndSetImage(byte[] pdf){
PdfReader reader = new PdfReader(pdf)
ByteArrayOutputStream output = new ByteArrayOutputStream()
def stamper = new PdfStamper(reader, output)
AcroFields form= stamper.getAcroFields()
form.setField(‘Address’, ‘Noida, India – 201301’) //Set the form field
PdfContentByte content = stamper.getOverContent(reader.getNumberOfPages())
Image image = Image.getInstance(new URL("Absolute URL to the image to be embedded"))

return output.toByteArray() //returns the Byte Array of the PDF contents

And the calling method had code which looked like this :

File file = new File(‘/home/vivek/filledForm.pdf’) //File to which the filled pdf will be written
file.bytes = populateFieldsAndSetImage(new File(‘/home/vivek/form.pdf’).bytes) // set the bytes of filledForm.pdf with the byte array returned by populateFieldsAndSetImage()

The PDF had pre-filled forms and the identification image also got inserted.

Hope this helps.


comments (2)

  1. Sansuns

    Nice article, I have seen some PDF forms especially used in the public service area, are created with a password to protects its originality instead of the embedded data matrix image. If its protected by a password, can we still put a overlay of data to the form without making any changes to the original form layout?>

  2. Arbind


    can you please tell me how can i upload image from groovy class to our database ?

    we are using my sql

    Thanking you


Leave a Reply

Your email address will not be published. Required fields are marked *