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
1/**
2 *
3 */
4
5import java.io.FileOutputStream;
6import java.io.IOException;
7
8import com.lowagie.text.DocumentException;
9import com.lowagie.text.pdf.AcroFields;
10import com.lowagie.text.pdf.PdfReader;
11import com.lowagie.text.pdf.PdfStamper;
12
13/**
14 * @author andyjarrett
15 *
16 */
17public class SimpleRegistrationForm {
18
19 /**
20 * @param args
21 * @throws IOException
22 * @throws DocumentException
23 */
24 public static void main(String[] args) throws IOException, DocumentException {
25
26 PdfReader reader = new PdfReader(
27 "/dir/to/pdf/SimpleRegistrationForm.pdf");
28 PdfStamper filledOutForm = new PdfStamper(reader, new FileOutputStream(
29 "/dir/to/pdf/filledOutForm.pdf"));
30
31 AcroFields form = filledOutForm.getAcroFields();
32 form.setField("name", "Andy Jarrett");
33 form.setField("address", "1 infinite road");
34 form.setField("postal_code", "1SW");
35 form.setField("email", "mail@example.com");
36
37 filledOutForm.close();
38 }
39
40}
2 *
3 */
4
5import java.io.FileOutputStream;
6import java.io.IOException;
7
8import com.lowagie.text.DocumentException;
9import com.lowagie.text.pdf.AcroFields;
10import com.lowagie.text.pdf.PdfReader;
11import com.lowagie.text.pdf.PdfStamper;
12
13/**
14 * @author andyjarrett
15 *
16 */
17public class SimpleRegistrationForm {
18
19 /**
20 * @param args
21 * @throws IOException
22 * @throws DocumentException
23 */
24 public static void main(String[] args) throws IOException, DocumentException {
25
26 PdfReader reader = new PdfReader(
27 "/dir/to/pdf/SimpleRegistrationForm.pdf");
28 PdfStamper filledOutForm = new PdfStamper(reader, new FileOutputStream(
29 "/dir/to/pdf/filledOutForm.pdf"));
30
31 AcroFields form = filledOutForm.getAcroFields();
32 form.setField("name", "Andy Jarrett");
33 form.setField("address", "1 infinite road");
34 form.setField("postal_code", "1SW");
35 form.setField("email", "mail@example.com");
36
37 filledOutForm.close();
38 }
39
40}
http://cfsearching.blogspot.com/search/label/iText...
- Leigh