KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > BatchFormFill


1 import org.faceless.pdf2.*;
2 import java.io.*;
3
4 // This demo is a mockup of a fairly typical case - a template is loaded
5
// and multiple copies are created with different data. Typically this
6
// would be run from a Servlet or similar.
7
//
8
public class BatchFormFill
9 {
10     // A simple "Person" object, which we will use to populate the
11
// template
12
//
13
private static class Person
14     {
15         public final String JavaDoc name, country, phone;
16
17     public Person(String JavaDoc name, String JavaDoc country, String JavaDoc phone)
18     {
19         this.name=name;
20         this.country=country;
21         this.phone=phone;
22     }
23     }
24
25     // The main program creates some people as test data, loads the
26
// template and the loops round each person, creating a form
27
// for them.
28
//
29
public static void main(String JavaDoc[] args) throws IOException
30     {
31     Person[] people = { new Person("John Bull", "UK", "442078868199"),
32                 new Person("Ben Franklin", "US", "12125551234"),
33                 new Person("Werner Graf", "DE", "49691234567"),
34                 new Person("Jean Reno", "FR", "3325123916"),
35                 new Person("Dmitri Papadolou", "GR", "3017891234")
36                 };
37
38     FileInputStream in = new FileInputStream("resources/fw8eci.pdf");
39         PDF template = new PDF(new PDFReader(in));
40     in.close();
41
42     for (int i=0;i<people.length;i++) {
43         createPDF(i, people[i], template);
44     }
45     }
46
47     // Create a form for the person from the supplied template,
48
// and write it to a file called "BatchForm-i.pdf", where "i"
49
// is the persons record number.
50
//
51
static final void createPDF(int i, Person person, PDF template) throws IOException
52     {
53     // First we clone the PDF, so we're not writing to the
54
// original template. In this fairly simple example this is
55
// not really necessary, as all we're doing it filling out
56
// form fields. More complex example might add bookmarks,
57
// add or remove pages and so on, in which case leaving an
58
// unaltered original is a good idea.
59
//
60

61     PDF pdf = new PDF(template);
62     Form form = pdf.getForm();
63     ((FormText)form.getElement("f1-1")).setValue(person.name);
64     ((FormText)form.getElement("f1-2")).setValue(person.country);
65     ((FormText)form.getElement("f1-3")).setValue(person.phone);
66
67     // Flattening the form shaves about 28k off the document size
68
// in this case, although it does mean the values are permanently
69
// part of the PDF.
70
//
71
form.flatten();
72
73     System.out.println("Writing \"BatchForm-"+i+".pdf\"");
74     FileOutputStream out = new FileOutputStream("BatchForm-"+i+".pdf");
75     pdf.render(out);
76     out.close();
77     }
78 }
79
Popular Tags