Using forms for reporting

Tags: merge documentsformsPdfCopymerge fieldsPdfSmartCopyiText 7

A series of examples that allow you to create reports using forms.

These examples were used to answer questions such as:

Files: 
/*
 
    This file is part of the iText (R) project.
    Copyright (c) 1998-2016 iText Group NV
 
*/
 
/**
 * Example written by Bruno Lowagie in answer to
 * http://stackoverflow.com/questions/26174675/copy-pdf-with-annotations-using-itext
 */
package com.itextpdf.samples.sandbox.acroforms;
 
import com.itextpdf.forms.PdfPageFormCopier;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.samples.GenericTest;
import com.itextpdf.test.annotations.type.SampleTest;
import org.junit.experimental.categories.Category;
 
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
 
@Category(SampleTest.class)
public class MergeForms extends GenericTest {
    public static final String DEST = "./target/test/resources/sandbox/acroforms/merge_forms.pdf";
    public static final String SRC1 = "./src/test/resources/pdfs/subscribe.pdf";
    public static final String SRC2 = "./src/test/resources/pdfs/state.pdf";
 
    public static void main(String[] args) throws Exception {
        File file = new File(DEST);
        file.getParentFile().mkdirs();
        new MergeForms().manipulatePdf(DEST);
    }
 
    @Override
    protected void manipulatePdf(String dest) throws Exception {
        PdfReader[] readers = {
                new PdfReader(getFile1()),
                new PdfReader(getFile2())
        };
        manipulatePdf(dest, readers);
    }
 
    protected void manipulatePdf(String dest, PdfReader[] readers) throws FileNotFoundException {
        PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
        pdfDoc.initializeOutlines();
        for (PdfReader reader : readers) {
            PdfDocument readerDoc = new PdfDocument(reader);
            readerDoc.copyPagesTo(1, readerDoc.getNumberOfPages(), pdfDoc, new PdfPageFormCopier());
            readerDoc.close();
        }
        pdfDoc.close();
    }
 
    public String getFile1() {
        return SRC1;
    }
 
    public String getFile2() {
        return SRC2;
    }
}
/*
 
    This file is part of the iText (R) project.
    Copyright (c) 1998-2016 iText Group NV
 
*/
 
/**
 * Example written by Bruno Lowagie in answer to
 * http://stackoverflow.com/questions/26174675/copy-pdf-with-annotations-using-itext
 */
package com.itextpdf.samples.sandbox.acroforms;
 
import com.itextpdf.forms.PdfAcroForm;
import com.itextpdf.forms.PdfPageFormCopier;
import com.itextpdf.forms.fields.PdfFormField;
import com.itextpdf.io.source.ByteArrayOutputStream;
import com.itextpdf.io.source.RandomAccessSourceFactory;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.ReaderProperties;
import com.itextpdf.samples.GenericTest;
import com.itextpdf.test.annotations.type.SampleTest;
import org.junit.experimental.categories.Category;
 
import java.io.File;
import java.io.IOException;
 
@Category(SampleTest.class)
public class MergeForms2 extends GenericTest {
    public static final String DEST = "./target/test/resources/sandbox/acroforms/merge_forms2.pdf";
    public static final String SRC = "./src/test/resources/pdfs/state.pdf";
 
    public static void main(String[] args) throws Exception {
        File file = new File(DEST);
        file.getParentFile().mkdirs();
        new MergeForms2().manipulatePdf(DEST);
    }
 
    @Override
    protected void manipulatePdf(String dest) throws Exception {
        PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
        pdfDoc.initializeOutlines();
        for (int i = 0; i < 3; ) {
            PdfDocument readerDoc = new PdfDocument(new PdfReader(
                    new RandomAccessSourceFactory().createSource(renameFields(SRC, ++i)),
                    new ReaderProperties()));
            readerDoc.copyPagesTo(1, readerDoc.getNumberOfPages(), pdfDoc, new PdfPageFormCopier());
            readerDoc.close();
        }
        pdfDoc.close();
    }
 
    protected byte[] renameFields(String src, int i) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfDocument pdfDoc = new PdfDocument(new PdfReader(src), new PdfWriter(baos));
 
        PdfAcroForm form = PdfAcroForm.getAcroForm(pdfDoc, true);
        for (PdfFormField field : form.getFormFields().values()) {
            field.setFieldName(String.format("%s_%d", field.getFieldName().toString(), i));
        }
 
        pdfDoc.close();
        return baos.toByteArray();
    }
}
/*
 
    This file is part of the iText (R) project.
    Copyright (c) 1998-2016 iText Group NV
 
*/
 
package com.itextpdf.samples.sandbox.acroforms.reporting;
 
import com.itextpdf.forms.PdfAcroForm;
import com.itextpdf.forms.PdfPageFormCopier;
import com.itextpdf.forms.fields.PdfFormField;
import com.itextpdf.io.source.ByteArrayOutputStream;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.samples.GenericTest;
import com.itextpdf.test.annotations.type.SampleTest;
import org.junit.experimental.categories.Category;
 
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileReader;
import java.util.Map;
import java.util.StringTokenizer;
 
@Category(SampleTest.class)
public class FillFlattenMerge1 extends GenericTest {
    public static final String DEST = "./target/test/resources/sandbox/acroforms/reporting/fill_flatten_merge1.pdf";
    public static final String DATA = "./src/test/resources/data/united_states.csv";
    public static final String SRC = "./src/test/resources/pdfs/state.pdf";
 
    public static void main(String[] args) throws Exception {
        File file = new File(DEST);
        file.getParentFile().mkdirs();
        new FillFlattenMerge1().manipulatePdf(DEST);
    }
 
    @Override
    protected void manipulatePdf(String dest) throws Exception {
        PdfDocument pdfDoc = new PdfDocument(new PdfWriter(DEST));
        pdfDoc.initializeOutlines();
 
        ByteArrayOutputStream baos;
        PdfDocument pdfInnerDoc;
        Map<String, PdfFormField> fields;
        PdfAcroForm form;
        StringTokenizer tokenizer;
 
        BufferedReader br = new BufferedReader(new FileReader(DATA));
        String line = br.readLine();
        while ((line = br.readLine()) != null) {
            // create a PDF in memory
            baos = new ByteArrayOutputStream();
            pdfInnerDoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(baos));
            form = PdfAcroForm.getAcroForm(pdfInnerDoc, true);
            tokenizer = new StringTokenizer(line, ";");
            fields = form.getFormFields();
            fields.get("name").setValue(tokenizer.nextToken());
            fields.get("abbr").setValue(tokenizer.nextToken());
            fields.get("capital").setValue(tokenizer.nextToken());
            fields.get("city").setValue(tokenizer.nextToken());
            fields.get("population").setValue(tokenizer.nextToken());
            fields.get("surface").setValue(tokenizer.nextToken());
            fields.get("timezone1").setValue(tokenizer.nextToken());
            fields.get("timezone2").setValue(tokenizer.nextToken());
            fields.get("dst").setValue(tokenizer.nextToken());
            form.flattenFields();
            pdfInnerDoc.close();
 
            pdfInnerDoc = new PdfDocument(new PdfReader(new ByteArrayInputStream(baos.toByteArray())));
            pdfInnerDoc.copyPagesTo(1, pdfInnerDoc.getNumberOfPages(), pdfDoc, new PdfPageFormCopier());
            pdfInnerDoc.close();
        }
        br.close();
 
        pdfDoc.close();
    }
}
/*
 
    This file is part of the iText (R) project.
    Copyright (c) 1998-2016 iText Group NV
 
*/
 
package com.itextpdf.samples.sandbox.acroforms.reporting;
 
import com.itextpdf.forms.PdfAcroForm;
import com.itextpdf.forms.PdfPageFormCopier;
import com.itextpdf.forms.fields.PdfFormField;
import com.itextpdf.io.source.ByteArrayOutputStream;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.samples.GenericTest;
import com.itextpdf.test.annotations.type.SampleTest;
import org.junit.experimental.categories.Category;
 
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileReader;
import java.util.Map;
import java.util.StringTokenizer;
 
@Category(SampleTest.class)
public class FillFlattenMerge2 extends GenericTest {
    public static final String DEST = "./target/test/resources/sandbox/acroforms/reporting/fill_flatten_merge2.pdf";
    public static final String DATA = "./src/test/resources/data/united_states.csv";
    public static final String SRC = "./src/test/resources/pdfs/state.pdf";
 
    public static void main(String[] args) throws Exception {
        File file = new File(DEST);
        file.getParentFile().mkdirs();
        new FillFlattenMerge2().manipulatePdf(DEST);
    }
 
    @Override
    protected void manipulatePdf(String dest) throws Exception {
        PdfWriter writer = new PdfWriter(DEST);
        writer.setSmartMode(true);
        PdfDocument pdfDoc = new PdfDocument(writer);
        pdfDoc.initializeOutlines();
 
        ByteArrayOutputStream baos;
        PdfReader reader;
        PdfDocument pdfInnerDoc;
        Map<String, PdfFormField> fields;
        PdfAcroForm form;
        StringTokenizer tokenizer;
 
        BufferedReader br = new BufferedReader(new FileReader(DATA));
        String line = br.readLine();
        while ((line = br.readLine()) != null) {
            // create a PDF in memory
            baos = new ByteArrayOutputStream();
            reader = new PdfReader(SRC);
            pdfInnerDoc = new PdfDocument(reader, new PdfWriter(baos));
            form = PdfAcroForm.getAcroForm(pdfInnerDoc, true);
            tokenizer = new StringTokenizer(line, ";");
            fields = form.getFormFields();
            fields.get("name").setValue(tokenizer.nextToken());
            fields.get("abbr").setValue(tokenizer.nextToken());
            fields.get("capital").setValue(tokenizer.nextToken());
            fields.get("city").setValue(tokenizer.nextToken());
            fields.get("population").setValue(tokenizer.nextToken());
            fields.get("surface").setValue(tokenizer.nextToken());
            fields.get("timezone1").setValue(tokenizer.nextToken());
            fields.get("timezone2").setValue(tokenizer.nextToken());
            fields.get("dst").setValue(tokenizer.nextToken());
            form.flattenFields();
            pdfInnerDoc.close();
 
            pdfInnerDoc = new PdfDocument(new PdfReader(new ByteArrayInputStream(baos.toByteArray())));
            pdfInnerDoc.copyPagesTo(1, pdfInnerDoc.getNumberOfPages(), pdfDoc, new PdfPageFormCopier());
            pdfInnerDoc.close();
        }
        br.close();
 
        pdfDoc.close();
    }
}
/*
 
    This file is part of the iText (R) project.
    Copyright (c) 1998-2016 iText Group NV
 
*/
 
/**
 * This example was written by Bruno Lowagie in answer to the following question:
 * http://stackoverflow.com/questions/24270195/wrapping-of-arabic-text-using-acrofields-in-itext-5-5
 */
package com.itextpdf.samples.sandbox.acroforms.reporting;
 
import com.itextpdf.forms.PdfAcroForm;
import com.itextpdf.forms.fields.PdfFormField;
import com.itextpdf.io.font.FontConstants;
import com.itextpdf.kernel.events.Event;
import com.itextpdf.kernel.events.IEventHandler;
import com.itextpdf.kernel.events.PdfDocumentEvent;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.itextpdf.kernel.pdf.xobject.PdfFormXObject;
import com.itextpdf.layout.Canvas;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.property.TextAlignment;
import com.itextpdf.layout.property.VerticalAlignment;
import com.itextpdf.samples.GenericTest;
import com.itextpdf.test.annotations.type.SampleTest;
import org.junit.experimental.categories.Category;
 
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;
 
@Category(SampleTest.class)
public class FillFlattenMerge3 extends GenericTest {
    public static final String DEST = "./target/test/resources/sandbox/acroforms/reporting/fill_flatten_merge3.pdf";
    public static final String DATA = "./src/test/resources/data/united_states.csv";
    public static final String[] FIELDS = {
            "name", "abbr", "capital", "city", "population", "surface", "timezone1", "timezone2", "dst"
    };
    public static final String SRC = "./src/test/resources/pdfs/state.pdf";
 
    protected Map<String, Rectangle> positions;
 
    public static void main(String[] args) throws Exception {
        File file = new File(DEST);
        file.getParentFile().mkdirs();
        new FillFlattenMerge3().manipulatePdf(DEST);
    }
 
    @Override
    protected void manipulatePdf(String dest) throws Exception {
        PdfDocument srcDoc = new PdfDocument(new PdfReader(SRC));
        PdfAcroForm form = PdfAcroForm.getAcroForm(srcDoc, true);
        positions = new HashMap<>();
        Map<String, PdfFormField> fields = form.getFormFields();
        for (PdfFormField field : fields.values()) {
            positions.put(field.getFieldName().getValue(), field.getWidgets().get(0).getRectangle().toRectangle());
        }
 
        PdfDocument pdfDoc = new PdfDocument(new PdfWriter(DEST));
        Document doc = new Document(pdfDoc);
        PdfFont font = PdfFontFactory.createFont(FontConstants.HELVETICA);
        pdfDoc.addEventHandler(PdfDocumentEvent.END_PAGE, new PaginationEventHandler(srcDoc.getFirstPage().copyAsFormXObject(pdfDoc)));
        srcDoc.close();
 
        StringTokenizer tokenizer;
        BufferedReader br = new BufferedReader(new FileReader(DATA));
        String line = br.readLine();
        while ((line = br.readLine()) != null) {
            pdfDoc.addNewPage();
            int i = 0;
            tokenizer = new StringTokenizer(line, ";");
            while (tokenizer.hasMoreTokens()) {
                process(doc, FIELDS[i++], tokenizer.nextToken(), font);
            }
        }
        br.close();
 
        doc.close();
    }
 
    protected void process(Document doc, String name, String value, PdfFont font) {
        Rectangle rect = positions.get(name);
        Paragraph p = new Paragraph(value).setFont(font).setFontSize(10);
        doc.showTextAligned(p, rect.getLeft() + 2, rect.getBottom() + 2, doc.getPdfDocument().getNumberOfPages(),
                TextAlignment.LEFT, VerticalAlignment.BOTTOM, 0);
    }
 
 
    protected class PaginationEventHandler implements IEventHandler {
        PdfFormXObject background;
 
        public PaginationEventHandler(PdfFormXObject background) throws IOException {
            this.background = background;
        }
 
        @Override
        public void handleEvent(Event event) {
            PdfDocument pdfDoc = ((PdfDocumentEvent) event).getDocument();
            int pageNum = pdfDoc.getPageNumber(((PdfDocumentEvent) event).getPage());
            // Add the background
            PdfCanvas canvas = new PdfCanvas(pdfDoc.getPage(pageNum).newContentStreamBefore(),
                    ((PdfDocumentEvent) event).getPage().getResources(), pdfDoc)
                    .addXObject(background, 0, 0);
            // Add the page number
            new Canvas(canvas, pdfDoc, ((PdfDocumentEvent) event).getPage().getPageSize())
                    .showTextAligned("page " + pageNum, 550, 800, TextAlignment.RIGHT);
        }
    }
}
/*
 
    This file is part of the iText (R) project.
    Copyright (c) 1998-2016 iText Group NV
 
*/
 
package com.itextpdf.samples.sandbox.acroforms.reporting;
 
import com.itextpdf.forms.PdfAcroForm;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.samples.GenericTest;
import com.itextpdf.test.annotations.type.SampleTest;
import org.junit.experimental.categories.Category;
 
import java.io.File;
 
@Category(SampleTest.class)
public class FillForm extends GenericTest {
    public static final String DEST = "./target/test/resources/sandbox/acroforms/reporting/fill_form.pdf";
    public static final String SRC = "./src/test/resources/pdfs/state.pdf";
 
    public static void main(String[] args) throws Exception {
        File file = new File(DEST);
        file.getParentFile().mkdirs();
        new FillForm().manipulatePdf(DEST);
    }
 
    @Override
    protected void manipulatePdf(String dest) throws Exception {
        PdfDocument pdfDoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(DEST));
        PdfAcroForm form = PdfAcroForm.getAcroForm(pdfDoc, true);
 
        form.getField("name").setValue("CALIFORNIA");
        form.getField("abbr").setValue("CA");
        form.getField("capital").setValue("Sacramento");
        form.getField("city").setValue("Los Angeles");
        form.getField("population").setValue("36,961,664");
        form.getField("surface").setValue("163,707");
        form.getField("timezone1").setValue("PT (UTC-8)");
        form.getField("timezone2").setValue("-");
        form.getField("dst").setValue("YES");
 
        pdfDoc.close();
    }
}
/*
 
    This file is part of the iText (R) project.
    Copyright (c) 1998-2016 iText Group NV
 
*/
 
package com.itextpdf.samples.sandbox.acroforms.reporting;
 
import com.itextpdf.forms.PdfAcroForm;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.samples.GenericTest;
import com.itextpdf.test.annotations.type.SampleTest;
import org.junit.experimental.categories.Category;
 
import java.io.File;
 
@Category(SampleTest.class)
public class FlattenForm extends GenericTest {
    public static final String DEST = "./target/test/resources/sandbox/acroforms/reporting/flatten_form.pdf";
    public static final String SRC = "./src/test/resources/pdfs/state.pdf";
 
    public static void main(String[] args) throws Exception {
        File file = new File(DEST);
        file.getParentFile().mkdirs();
        new FlattenForm().manipulatePdf(DEST);
    }
 
    @Override
    protected void manipulatePdf(String dest) throws Exception {
        PdfDocument pdfDoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(DEST));
        PdfAcroForm form = PdfAcroForm.getAcroForm(pdfDoc, true);
 
        form.getField("name").setValue("CALIFORNIA");
        form.getField("abbr").setValue("CA");
        form.getField("capital").setValue("Sacramento");
        form.getField("city").setValue("Los Angeles");
        form.getField("population").setValue("36,961,664");
        form.getField("surface").setValue("163,707");
        form.getField("timezone1").setValue("PT (UTC-8)");
        form.getField("timezone2").setValue("-");
        form.getField("dst").setValue("YES");
 
        form.flattenFields();
 
        pdfDoc.close();
    }
}
Resources: 
File nameRaw URLUpdated
united_states.csvunited_states.csv2016-08-08 4:44 pm
state.pdfstate.pdf2016-08-10 11:52 am
subscribe.pdfsubscribe.pdf2016-08-09 2:59 pm