Using forms for reporting

This is a code example of iText PDF, discover more.

30th October 2015
admin-marketing

Switch code for this example

FillForm.java
  1. package sandbox.acroforms.reporting;
  2.  
  3. import com.itextpdf.text.DocumentException;
  4. import com.itextpdf.text.pdf.AcroFields;
  5. import com.itextpdf.text.pdf.PdfReader;
  6. import com.itextpdf.text.pdf.PdfStamper;
  7.  
  8. import java.io.File;
  9. import java.io.FileOutputStream;
  10. import java.io.IOException;
  11.  
  12. import sandbox.WrapToTest;
  13.  
  14. @WrapToTest(compareRenders = true)
  15. public class FillForm {
  16.  
  17.     public static final String SRC = "resources/pdfs/state.pdf";
  18.     public static final String DEST = "results/acroforms/reporting/california.pdf";
  19.  
  20.     public static void main(String[] args) throws IOException, DocumentException {
  21.         File file = new File(DEST);
  22.         file.getParentFile().mkdirs();
  23.         new FillForm().manipulatePdf(SRC, DEST);
  24.     }
  25.     public void manipulatePdf(String src, String dest) throws DocumentException, IOException {
  26.         PdfReader reader = new PdfReader(src);
  27.         PdfStamper stamper = new PdfStamper(reader,
  28.                 new FileOutputStream(dest));
  29.         AcroFields fields = stamper.getAcroFields();
  30.         fields.setField("name", "CALIFORNIA");
  31.         fields.setField("abbr", "CA");
  32.         fields.setField("capital", "Sacramento");
  33.         fields.setField("city", "Los Angeles");
  34.         fields.setField("population", "36,961,664");
  35.         fields.setField("surface", "163,707");
  36.         fields.setField("timezone1", "PT (UTC-8)");
  37.         fields.setField("timezone2", "-");
  38.         fields.setField("dst", "YES");
  39.         stamper.close();
  40.         reader.close();
  41.     }
  42. }
FlattenForm.java
  1. package sandbox.acroforms.reporting;
  2.  
  3. import com.itextpdf.text.DocumentException;
  4. import com.itextpdf.text.pdf.AcroFields;
  5. import com.itextpdf.text.pdf.PdfReader;
  6. import com.itextpdf.text.pdf.PdfStamper;
  7.  
  8. import java.io.File;
  9. import java.io.FileOutputStream;
  10. import java.io.IOException;
  11.  
  12. import sandbox.WrapToTest;
  13.  
  14. @WrapToTest(compareRenders = true)
  15. public class FlattenForm {
  16.  
  17.     public static final String SRC = "resources/pdfs/state.pdf";
  18.     public static final String DEST = "results/acroforms/reporting/california2.pdf";
  19.  
  20.     public static void main(String[] args) throws IOException, DocumentException {
  21.         File file = new File(DEST);
  22.         file.getParentFile().mkdirs();
  23.         new FlattenForm().manipulatePdf(SRC, DEST);
  24.     }
  25.     public void manipulatePdf(String src, String dest) throws DocumentException, IOException {
  26.         PdfReader reader = new PdfReader(src);
  27.         PdfStamper stamper = new PdfStamper(reader,
  28.                 new FileOutputStream(dest));
  29.         AcroFields fields = stamper.getAcroFields();
  30.         fields.setField("name", "CALIFORNIA");
  31.         fields.setField("abbr", "CA");
  32.         fields.setField("capital", "Sacramento");
  33.         fields.setField("city", "Los Angeles");
  34.         fields.setField("population", "36,961,664");
  35.         fields.setField("surface", "163,707");
  36.         fields.setField("timezone1", "PT (UTC-8)");
  37.         fields.setField("timezone2", "-");
  38.         fields.setField("dst", "YES");
  39.         stamper.setFormFlattening(true);
  40.         stamper.close();
  41.         reader.close();
  42.     }
  43. }
FillFlattenMerge1.java
  1. package sandbox.acroforms.reporting;
  2.  
  3. import com.itextpdf.text.Document;
  4. import com.itextpdf.text.DocumentException;
  5. import com.itextpdf.text.pdf.AcroFields;
  6. import com.itextpdf.text.pdf.PdfCopy;
  7. import com.itextpdf.text.pdf.PdfReader;
  8. import com.itextpdf.text.pdf.PdfStamper;
  9.  
  10. import java.io.BufferedReader;
  11. import java.io.ByteArrayOutputStream;
  12. import java.io.File;
  13. import java.io.FileOutputStream;
  14. import java.io.FileReader;
  15. import java.io.IOException;
  16. import java.util.StringTokenizer;
  17.  
  18. import sandbox.WrapToTest;
  19.  
  20. @WrapToTest(compareRenders = true)
  21. public class FillFlattenMerge1 {
  22.  
  23.     public static final String SRC = "resources/pdfs/state.pdf";
  24.     public static final String DEST = "results/acroforms/reporting/united_states_1.pdf";
  25.     public static final String DATA = "resources/data/united_states.csv";
  26.  
  27.     public static void main(String[] args) throws IOException, DocumentException {
  28.         File file = new File(DEST);
  29.         file.getParentFile().mkdirs();
  30.         new FillFlattenMerge1().manipulatePdf(SRC, DEST);
  31.     }
  32.  
  33.     public void manipulatePdf(String src, String dest) throws DocumentException, IOException {
  34.         Document document = new Document();
  35.         // Using PdfCopy isn't a good idea in this use case.
  36.         // Take a look at FillFlattenMerge2 to find out how to do it right!
  37.         PdfCopy copy = new PdfCopy(document, new FileOutputStream(dest));
  38.         document.open();
  39.         ByteArrayOutputStream baos;
  40.         PdfReader reader;
  41.         PdfStamper stamper;
  42.         AcroFields fields;
  43.         StringTokenizer tokenizer;
  44.         BufferedReader br = new BufferedReader(new FileReader(DATA));
  45.         String line = br.readLine();
  46.         while ((line = br.readLine()) != null) {
  47.             // create a PDF in memory
  48.             baos = new ByteArrayOutputStream();
  49.             reader = new PdfReader(SRC);
  50.             stamper = new PdfStamper(reader, baos);
  51.             fields = stamper.getAcroFields();
  52.             tokenizer = new StringTokenizer(line, ";");
  53.             fields.setField("name", tokenizer.nextToken());
  54.             fields.setField("abbr", tokenizer.nextToken());
  55.             fields.setField("capital", tokenizer.nextToken());
  56.             fields.setField("city", tokenizer.nextToken());
  57.             fields.setField("population", tokenizer.nextToken());
  58.             fields.setField("surface", tokenizer.nextToken());
  59.             fields.setField("timezone1", tokenizer.nextToken());
  60.             fields.setField("timezone2", tokenizer.nextToken());
  61.             fields.setField("dst", tokenizer.nextToken());
  62.             stamper.setFormFlattening(true);
  63.             stamper.close();
  64.             reader.close();
  65.             // add the PDF to PdfCopy
  66.             reader = new PdfReader(baos.toByteArray());
  67.             copy.addDocument(reader);
  68.             reader.close();
  69.         }
  70.         br.close();
  71.         document.close();
  72.     }
  73. }
FillFlattenMerge2.java
  1. package sandbox.acroforms.reporting;
  2.  
  3. import com.itextpdf.text.Document;
  4. import com.itextpdf.text.DocumentException;
  5. import com.itextpdf.text.pdf.AcroFields;
  6. import com.itextpdf.text.pdf.PdfCopy;
  7. import com.itextpdf.text.pdf.PdfReader;
  8. import com.itextpdf.text.pdf.PdfSmartCopy;
  9. import com.itextpdf.text.pdf.PdfStamper;
  10.  
  11. import java.io.BufferedReader;
  12. import java.io.ByteArrayOutputStream;
  13. import java.io.File;
  14. import java.io.FileOutputStream;
  15. import java.io.FileReader;
  16. import java.io.IOException;
  17. import java.util.StringTokenizer;
  18.  
  19. import sandbox.WrapToTest;
  20.  
  21. @WrapToTest(compareRenders = true)
  22. public class FillFlattenMerge2 {
  23.  
  24.     public static final String SRC = "resources/pdfs/state.pdf";
  25.     public static final String DEST = "results/acroforms/reporting/united_states_2.pdf";
  26.     public static final String DATA = "resources/data/united_states.csv";
  27.  
  28.     public static void main(String[] args) throws IOException, DocumentException {
  29.         File file = new File(DEST);
  30.         file.getParentFile().mkdirs();
  31.         new FillFlattenMerge2().manipulatePdf(SRC, DEST);
  32.     }
  33.  
  34.     public void manipulatePdf(String src, String dest) throws DocumentException, IOException {
  35.         Document document = new Document();
  36.         PdfCopy copy = new PdfSmartCopy(document, new FileOutputStream(dest));
  37.         document.open();
  38.         ByteArrayOutputStream baos;
  39.         PdfReader reader;
  40.         PdfStamper stamper;
  41.         AcroFields fields;
  42.         StringTokenizer tokenizer;
  43.         BufferedReader br = new BufferedReader(new FileReader(DATA));
  44.         String line = br.readLine();
  45.         while ((line = br.readLine()) != null) {
  46.             // create a PDF in memory
  47.             baos = new ByteArrayOutputStream();
  48.             reader = new PdfReader(SRC);
  49.             stamper = new PdfStamper(reader, baos);
  50.             fields = stamper.getAcroFields();
  51.             tokenizer = new StringTokenizer(line, ";");
  52.             fields.setField("name", tokenizer.nextToken());
  53.             fields.setField("abbr", tokenizer.nextToken());
  54.             fields.setField("capital", tokenizer.nextToken());
  55.             fields.setField("city", tokenizer.nextToken());
  56.             fields.setField("population", tokenizer.nextToken());
  57.             fields.setField("surface", tokenizer.nextToken());
  58.             fields.setField("timezone1", tokenizer.nextToken());
  59.             fields.setField("timezone2", tokenizer.nextToken());
  60.             fields.setField("dst", tokenizer.nextToken());
  61.             stamper.setFormFlattening(true);
  62.             stamper.close();
  63.             reader.close();
  64.             // add the PDF to PdfCopy
  65.             reader = new PdfReader(baos.toByteArray());
  66.             copy.addDocument(reader);
  67.             reader.close();
  68.         }
  69.         br.close();
  70.         document.close();
  71.     }
  72. }
FillFlattenMerge3.java
  1. package sandbox.acroforms.reporting;
  2.  
  3. import com.itextpdf.text.Document;
  4. import com.itextpdf.text.DocumentException;
  5. import com.itextpdf.text.Element;
  6. import com.itextpdf.text.Font;
  7. import com.itextpdf.text.Font.FontFamily;
  8. import com.itextpdf.text.Phrase;
  9. import com.itextpdf.text.Rectangle;
  10. import com.itextpdf.text.pdf.AcroFields;
  11. import com.itextpdf.text.pdf.ColumnText;
  12. import com.itextpdf.text.pdf.PdfContentByte;
  13. import com.itextpdf.text.pdf.PdfImportedPage;
  14. import com.itextpdf.text.pdf.PdfPageEventHelper;
  15. import com.itextpdf.text.pdf.PdfReader;
  16. import com.itextpdf.text.pdf.PdfWriter;
  17.  
  18. import java.io.BufferedReader;
  19. import java.io.File;
  20. import java.io.FileOutputStream;
  21. import java.io.FileReader;
  22. import java.io.IOException;
  23. import java.util.HashMap;
  24. import java.util.Map;
  25. import java.util.StringTokenizer;
  26.  
  27. import sandbox.WrapToTest;
  28.  
  29. @WrapToTest(compareRenders = true)
  30. public class FillFlattenMerge3 {
  31.  
  32.     public static final String SRC = "resources/pdfs/state.pdf";
  33.     public static final String DEST = "results/acroforms/reporting/united_states_3.pdf";
  34.     public static final String DATA = "resources/data/united_states.csv";
  35.     public static final String[] FIELDS = {
  36.         "name", "abbr", "capital", "city", "population", "surface", "timezone1", "timezone2", "dst"
  37.     };
  38.     public static final Font FONT = new Font(FontFamily.HELVETICA, 10);
  39.    
  40.     protected Map positions;
  41.    
  42.     public static void main(String[] args) throws IOException, DocumentException {
  43.         File file = new File(DEST);
  44.         file.getParentFile().mkdirs();
  45.         new FillFlattenMerge3().manipulatePdf(SRC, DEST);
  46.     }
  47.  
  48.     public class Background extends PdfPageEventHelper {
  49.  
  50.         PdfImportedPage background;
  51.        
  52.         public Background(PdfImportedPage background) {
  53.             this.background = background;
  54.         }
  55.        
  56.         @Override
  57.         public void onEndPage(PdfWriter writer, Document document) {
  58.             PdfContentByte cb = writer.getDirectContentUnder();
  59.             cb.addTemplate(background, 0, 0);
  60.             ColumnText.showTextAligned(cb, Element.ALIGN_RIGHT, new Phrase("page " + writer.getPageNumber()), 550, 800, 0);
  61.         }
  62.        
  63.     }
  64.    
  65.     public void manipulatePdf(String src, String dest) throws DocumentException, IOException {
  66.         PdfReader reader = new PdfReader(src);
  67.         AcroFields form = reader.getAcroFields();
  68.         positions = new HashMap();
  69.         Rectangle rectangle;
  70.         Map fields = form.getFields();
  71.         for (String name : fields.keySet()) {
  72.             rectangle = form.getFieldPositions(name).get(0).position;
  73.             positions.put(name, rectangle);
  74.         }
  75.        
  76.         Document document = new Document();
  77.         PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(dest));
  78.         writer.setPageEvent(new Background(writer.getImportedPage(reader, 1)));
  79.         document.open();
  80.  
  81.         PdfContentByte cb = writer.getDirectContent();
  82.         StringTokenizer tokenizer;
  83.         BufferedReader br = new BufferedReader(new FileReader(DATA));
  84.         String line = br.readLine();
  85.         while ((line = br.readLine()) != null) {
  86.             int i = 0;
  87.             tokenizer = new StringTokenizer(line, ";");
  88.             while (tokenizer.hasMoreTokens()) {
  89.                 process(cb, FIELDS[i++], tokenizer.nextToken());
  90.             }
  91.             document.newPage();
  92.         }
  93.         br.close();
  94.         document.close();
  95.        
  96.         reader.close();
  97.     }
  98.    
  99.     protected void process(PdfContentByte cb, String name, String value) throws DocumentException {
  100.         Rectangle rect = positions.get(name);
  101.         Phrase p = new Phrase(value, FONT);
  102.         ColumnText.showTextAligned(cb, Element.ALIGN_LEFT,
  103.                 p, rect.getLeft() + 2, rect.getBottom() + 2, 0);
  104.     }
  105. }
MergeForms.java
  1. package sandbox.acroforms;
  2.  
  3. import com.itextpdf.text.Document;
  4. import com.itextpdf.text.DocumentException;
  5. import com.itextpdf.text.pdf.PdfCopy;
  6. import com.itextpdf.text.pdf.PdfReader;
  7.  
  8. import java.io.File;
  9. import java.io.FileOutputStream;
  10. import java.io.IOException;
  11. import sandbox.WrapToTest;
  12.  
  13. @WrapToTest
  14. public class MergeForms {
  15.  
  16.     public static final String SRC1 = "resources/pdfs/subscribe.pdf";
  17.     public static final String SRC2 = "resources/pdfs/state.pdf";
  18.     public static final String DEST = "results/acroforms/merged_form.pdf";
  19.  
  20.     public static void main(String[] args) throws IOException, DocumentException {
  21.         File file = new File(DEST);
  22.         file.getParentFile().mkdirs();
  23.         new MergeForms().createPdf(DEST);
  24.     }
  25.    
  26.     public void createPdf(String filename, PdfReader[] readers) throws IOException, DocumentException {
  27.         Document document = new Document();
  28.         PdfCopy copy = new PdfCopy(document, new FileOutputStream(filename));
  29.         copy.setMergeFields();
  30.         document.open();
  31.         for (PdfReader reader : readers) {
  32.             copy.addDocument(reader);
  33.         }
  34.         document.close();
  35.         for (PdfReader reader : readers) {
  36.             reader.close();
  37.         }
  38.     }
  39.    
  40.     public void createPdf(String filename) throws IOException, DocumentException {
  41.         PdfReader[] readers = {
  42.             new PdfReader(getFile1()),
  43.             new PdfReader(getFile2())
  44.         };
  45.         createPdf(filename, readers);
  46.     }
  47.  
  48.     public String getFile1() { return SRC1; }
  49.     public String getFile2() { return SRC2; }
  50. }
MergeForms2.java
  1. package sandbox.acroforms;
  2.  
  3. import com.itextpdf.text.Document;
  4. import com.itextpdf.text.DocumentException;
  5. import com.itextpdf.text.pdf.AcroFields;
  6. import com.itextpdf.text.pdf.PdfCopy;
  7. import com.itextpdf.text.pdf.PdfReader;
  8. import com.itextpdf.text.pdf.PdfSmartCopy;
  9. import com.itextpdf.text.pdf.PdfStamper;
  10.  
  11. import java.io.ByteArrayOutputStream;
  12. import java.io.File;
  13. import java.io.FileOutputStream;
  14. import java.io.IOException;
  15. import java.util.ArrayList;
  16. import java.util.HashSet;
  17. import java.util.List;
  18. import java.util.Set;
  19.  
  20. import sandbox.WrapToTest;
  21.  
  22. @WrapToTest
  23. public class MergeForms2 {
  24.  
  25.     public static final String SRC = "resources/pdfs/state.pdf";
  26.     public static final String DEST = "results/acroforms/merged_form2.pdf";
  27.  
  28.     public static void main(String[] args) throws IOException, DocumentException {
  29.         File file = new File(DEST);
  30.         file.getParentFile().mkdirs();
  31.         new MergeForms2().manipulatePdf(SRC, DEST);
  32.     }
  33.    
  34.     public void manipulatePdf(String src, String dest) throws IOException, DocumentException {
  35.         Document document = new Document();
  36.         PdfCopy copy = new PdfSmartCopy(document, new FileOutputStream(dest));
  37.         copy.setMergeFields();
  38.         document.open();
  39.         List readers = new ArrayList();
  40.         for (int i = 0; i < 3; ) {
  41.             PdfReader reader = new PdfReader(renameFields(src, ++i));
  42.             readers.add(reader);
  43.             copy.addDocument(reader);
  44.         }
  45.         document.close();
  46.         for (PdfReader reader : readers) {
  47.             reader.close();
  48.         }
  49.     }
  50.    
  51.     public byte[] renameFields(String src, int i) throws IOException, DocumentException {
  52.         ByteArrayOutputStream baos = new ByteArrayOutputStream();
  53.         PdfReader reader = new PdfReader(src);
  54.         PdfStamper stamper = new PdfStamper(reader, baos);
  55.         AcroFields form = stamper.getAcroFields();
  56.         Set keys = new HashSet(form.getFields().keySet());
  57.         for (String key : keys) {
  58.             form.renameField(key, String.format("%s_%d", key, i));
  59.         }
  60.         stamper.close();
  61.         reader.close();
  62.         return baos.toByteArray();
  63.     }
  64. }
Contact

Still have questions? 

We're happy to answer your questions. Reach out to us and we'll get back to you shortly.

Contact us
Stay updated

Join 11,000+ subscribers and become an iText PDF expert by staying up to date with our new products, updates, tips, technical solutions and happenings.

Subscribe Now