How to fill out a pdf file programmatically? (AcroForm technology)

Tags: formsfill formiText 7

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 7 to fill it out like this:

PdfReader reader = new PdfReader(src);
PdfWriter writer = new PdfWriter(dest);
PdfDocument pdfDoc = new PdfDocument(reader, writer);
PdfAcroForm form = PdfAcroForm.getAcroForm(pdfDoc, true);
Map<String, PdfFormField> fields = form.getFormFields();
fields.get(key).setValue(value);
form.flattenFields();
pdfDoc.close();

In this snippet, src is the source of a PDF file 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 form.flattenFields(); 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 5.