Andy Jarrett // Code. Develop. Create.

PDF Form filling with java and iText

I've been looking at PDF form filling with Java so I can use it with Railo and I came across iText, a Free Java-PDF Library.

I couldn't find a simple explanation of populating a PDF form in java so my below example assumes you have a PDF called "SimpleRegistrationForm.pdf" and it has 4 fields in it: name, address, postal_code, and email The completed form will be saved to a file called filledOutForm.pdf

/** * */import java.io.FileOutputStream;import java.io.IOException;import com.lowagie.text.DocumentException;import com.lowagie.text.pdf.AcroFields;import com.lowagie.text.pdf.PdfReader;import com.lowagie.text.pdf.PdfStamper;/** * @author andyjarrett * */public class SimpleRegistrationForm { /** * @param args * @throws IOException * @throws DocumentException */ public static void main(String[] args) throws IOException, DocumentException { PdfReader reader = new PdfReader( "/dir/to/pdf/SimpleRegistrationForm.pdf"); PdfStamper filledOutForm = new PdfStamper(reader, new FileOutputStream( "/dir/to/pdf/filledOutForm.pdf")); AcroFields form = filledOutForm.getAcroFields(); form.setField("name", "Andy Jarrett"); form.setField("address", "1 infinite road"); form.setField("postal_code", "1SW"); form.setField("email", "[email protected]"); filledOutForm.close(); }}

I’m here, learning and working away. If you liked this content and want to keep me going, consider buying me a coffee. Your support keeps this site running and the coffee brewing! ☕️