How to fill out a PDF file programmatically? (AcroForm technology)
What techniques available to fill a PDF form automatically using external data and save them. I have to use data from a database to fill a template PDF and save a copy of it on disk with that data. Language and platform is not issue but it would be good if it can run on windows and Linux.
Posted on StackOverflow on Jun 24, 2010 by affan
If your form is based on AcroForm technology, you can use iText to fill it out like this:
PdfReader reader = new PdfReader(src);
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
AcroFields form = stamper.getAcroFields();
form.setField(key, value);
stamper.setFormFlattening(true);
stamper.close();
reader.close();
In this snippet, src
is the source of a PDF file (could be a path to a file, could be a byte[]
) and dest
is the path to the resulting PDF. The key
corresponds with the name of a field in your template. The value
corresponds with the value you want to fill in. If you want the form to keep its interactivity, you need to remove the line stamper.setFormFlattening(true);
otherwise all form fields will be removed, resulting in a flat PDF.
Click this link if you want to see how to answer this question in iText 7.