Skip to main content
Skip table of contents

Using forms for reporting

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

These examples were used to answer questions such as:

mergeforms

JAVA
/*
    This file is part of the iText (R) project.
    Copyright (c) 1998-2023 Apryse Group NV
    Authors: Apryse Software.

    For more information, please contact iText Software at this address:
    sales@itextpdf.com
 */
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 java.io.File;
import java.io.FileNotFoundException;

public class MergeForms {
    public static final String DEST = "./target/sandbox/acroforms/merge_forms.pdf";

    public static final String SRC1 = "./src/main/resources/pdfs/subscribe.pdf";
    public static final String SRC2 = "./src/main/resources/pdfs/state.pdf";

    public static void main(String[] args) throws Exception {
        File file = new File(DEST);
        file.getParentFile().mkdirs();

        new MergeForms().manipulatePdf(DEST);
    }

    public String getFile1() {
        return SRC1;
    }

    public String getFile2() {
        return SRC2;
    }

    protected void manipulatePdf(String dest) throws Exception {
        PdfReader[] readers = {
                new PdfReader(getFile1()),
                new PdfReader(getFile2())
        };

        // Method copies the content of all read files to the created resultant pdf
        mergePdfForms(dest, readers);
    }

    private void mergePdfForms(String dest, PdfReader[] readers) throws FileNotFoundException {
        PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));

        // This method initializes an outline tree of the document and sets outline mode to true.
        pdfDoc.initializeOutlines();

        // Copier contains the logic to copy only acroform fields to a new page.
        // PdfPageFormCopier uses some caching logic which can potentially improve performance
        // in case of the reusing of the same instance.
        PdfPageFormCopier formCopier = new PdfPageFormCopier();

        for (PdfReader reader : readers) {
            PdfDocument readerDoc = new PdfDocument(reader);
            readerDoc.copyPagesTo(1, readerDoc.getNumberOfPages(), pdfDoc, formCopier);
            readerDoc.close();
        }

        pdfDoc.close();
    }
}

MergeForms C#

C#
using System;
using System.IO;
using iText.Forms;
using iText.Kernel.Pdf;

namespace iText.Samples.Sandbox.Acroforms
{
    public class MergeForms
    {
        public static readonly String DEST = "results/sandbox/acroforms/merge_forms.pdf";

        public static readonly String SRC1 = "../../../resources/pdfs/subscribe.pdf";
        public static readonly String SRC2 = "../../../resources/pdfs/state.pdf";

        public static void Main(String[] args)
        {
            FileInfo file = new FileInfo(DEST);
            file.Directory.Create();

            new MergeForms().ManipulatePdf(DEST);
        }

        public virtual String GetFile1()
        {
            return SRC1;
        }

        public virtual String GetFile2()
        {
            return SRC2;
        }

        protected void ManipulatePdf(String dest)
        {
            PdfReader[] readers =
            {
                new PdfReader(GetFile1()),
                new PdfReader(GetFile2())
            };

            // Method copies the content of all read files to the created resultant pdf
            mergePdfForms(dest, readers);
        }

        private void mergePdfForms(String dest, PdfReader[] readers)
        {
            PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));

            // This method initializes an outline tree of the document and sets outline mode to true.
            pdfDoc.InitializeOutlines();

            // Copier contains the logic to copy only acroform fields to a new page.
            // PdfPageFormCopier uses some caching logic which can potentially improve performance
            // in case of the reusing of the same instance.
            PdfPageFormCopier formCopier = new PdfPageFormCopier();

            foreach (PdfReader reader in readers)
            {
                PdfDocument readerDoc = new PdfDocument(reader);
                readerDoc.CopyPagesTo(1, readerDoc.GetNumberOfPages(), pdfDoc, formCopier);
                readerDoc.Close();
            }

            pdfDoc.Close();
        }
    }
}

mergeforms2

JAVA
/*
    This file is part of the iText (R) project.
    Copyright (c) 1998-2023 Apryse Group NV
    Authors: Apryse Software.

    For more information, please contact iText Software at this address:
    sales@itextpdf.com
 */
package com.itextpdf.samples.sandbox.acroforms;

import com.itextpdf.forms.PdfAcroForm;
import com.itextpdf.forms.PdfPageFormCopier;
import com.itextpdf.forms.fields.PdfFormCreator;
import com.itextpdf.forms.fields.PdfFormField;
import com.itextpdf.io.source.ByteArrayOutputStream;
import com.itextpdf.io.source.IRandomAccessSource;
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 java.io.File;
import java.io.IOException;

public class MergeForms2 {
    public static final String DEST = "./target/sandbox/acroforms/merge_forms2.pdf";

    public static final String SRC = "./src/main/resources/pdfs/state.pdf";

    public static void main(String[] args) throws Exception {
        File file = new File(DEST);
        file.getParentFile().mkdirs();

        new MergeForms2().manipulatePdf(DEST);
    }

    protected void manipulatePdf(String dest) throws Exception {
        PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));

        // This method initializes an outline tree of the document and sets outline mode to true.
        pdfDoc.initializeOutlines();

        // Copier contains the logic to copy only acroform fields to a new page.
        // PdfPageFormCopier uses some caching logic which can potentially improve performance
        // in case of the reusing of the same instance.
        PdfPageFormCopier formCopier = new PdfPageFormCopier();

        for (int i = 0; i < 3; ) {

            // This method reads source pdf and renames form fields,
            // because the same source pdf with the same form fields will be copied.
            byte[] content = renameFields(SRC, ++i);
            IRandomAccessSource source  = new RandomAccessSourceFactory().createSource(content);
            PdfDocument readerDoc = new PdfDocument(new PdfReader(source, new ReaderProperties()));
            readerDoc.copyPagesTo(1, readerDoc.getNumberOfPages(), pdfDoc, formCopier);
            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 = PdfFormCreator.getAcroForm(pdfDoc, true);
        for (PdfFormField field : form.getAllFormFields().values()) {
            field.setFieldName(String.format("%s_%d", field.getFieldName().toString(), i));
        }

        pdfDoc.close();

        return baos.toByteArray();
    }
}

MergeForms2 C#

C#
using System;
using System.IO;
using iText.Forms;
using iText.Forms.Fields;
using iText.IO.Source;
using iText.Kernel.Pdf;

namespace iText.Samples.Sandbox.Acroforms
{
    public class MergeForms2
    {
        public static readonly String DEST = "results/sandbox/acroforms/merge_forms2.pdf";

        public static readonly String SRC = "../../../resources/pdfs/state.pdf";

        public static void Main(String[] args)
        {
            FileInfo file = new FileInfo(DEST);
            file.Directory.Create();

            new MergeForms2().ManipulatePdf(DEST);
        }

        protected void ManipulatePdf(String dest)
        {
            PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));

            // This method initializes an outline tree of the document and sets outline mode to true.
            pdfDoc.InitializeOutlines();

            // Copier contains the logic to copy only acroform fields to a new page.
            // PdfPageFormCopier uses some caching logic which can potentially improve performance
            // in case of the reusing of the same instance.
            PdfPageFormCopier formCopier = new PdfPageFormCopier();

            for (int i = 0; i < 3; i++)
            {
                // This method reads and renames form fields,
                // because the same source pdf with the same form fields will be copied.
                byte[] content = RenameFields(SRC, i + 1);
                IRandomAccessSource source = new RandomAccessSourceFactory().CreateSource(content);
                PdfDocument readerDoc = new PdfDocument(new PdfReader(source, new ReaderProperties()));
                readerDoc.CopyPagesTo(1, readerDoc.GetNumberOfPages(), pdfDoc, formCopier);
                readerDoc.Close();
            }

            pdfDoc.Close();
        }

        protected byte[] RenameFields(String src, int i)
        {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            PdfDocument pdfDoc = new PdfDocument(new PdfReader(src), new PdfWriter(baos));

            PdfAcroForm form = PdfFormCreator.GetAcroForm(pdfDoc, true);
            foreach (PdfFormField field in form.GetAllFormFields().Values)
            {
                field.SetFieldName(String.Format("{0}_{1}", field.GetFieldName().ToString(), i));
            }

            pdfDoc.Close();

            return baos.ToArray();
        }
    }
}

fillflattenmerge1

JAVA
/*
    This file is part of the iText (R) project.
    Copyright (c) 1998-2023 Apryse Group NV
    Authors: Apryse Software.

    For more information, please contact iText Software at this address:
    sales@itextpdf.com
 */
package com.itextpdf.samples.sandbox.acroforms.reporting;

import com.itextpdf.forms.PdfAcroForm;
import com.itextpdf.forms.PdfPageFormCopier;
import com.itextpdf.forms.fields.PdfFormCreator;
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 java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileReader;
import java.util.Map;
import java.util.StringTokenizer;

public class FillFlattenMerge1 {
    public static final String DEST = "./target/sandbox/acroforms/reporting/fill_flatten_merge1.pdf";

    public static final String DATA = "./src/main/resources/data/united_states.csv";
    public static final String SRC = "./src/main/resources/pdfs/state.pdf";

    public static void main(String[] args) throws Exception {
        File file = new File(DEST);
        file.getParentFile().mkdirs();

        new FillFlattenMerge1().manipulatePdf(DEST);
    }

    protected void manipulatePdf(String dest) throws Exception {
        PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
        PdfPageFormCopier formCopier = new PdfPageFormCopier();

        // Initialize an outline tree of the document and sets outline mode to true
        pdfDoc.initializeOutlines();

        try (BufferedReader br = new BufferedReader(new FileReader(DATA))) {

            // Read first line with headers,
            // do nothing with this line, because headers are already filled in form
            String line = br.readLine();

            while ((line = br.readLine()) != null) {

                // Create a PDF in memory
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                PdfDocument pdfInnerDoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(baos));
                PdfAcroForm form = PdfFormCreator.getAcroForm(pdfInnerDoc, true);

                // Parse text line and fill all fields of form
                fillAndFlattenForm(line, form);
                pdfInnerDoc.close();

                // Copy page with current filled form to the result pdf document
                pdfInnerDoc = new PdfDocument(new PdfReader(new ByteArrayInputStream(baos.toByteArray())));
                pdfInnerDoc.copyPagesTo(1, pdfInnerDoc.getNumberOfPages(), pdfDoc, formCopier);
                pdfInnerDoc.close();
            }
        }

        pdfDoc.close();
    }

    public void fillAndFlattenForm(String line, PdfAcroForm form) {
        StringTokenizer tokenizer = new StringTokenizer(line, ";");
        Map<String, PdfFormField> fields = form.getAllFormFields();

        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());

        // If no fields have been explicitly included via partialFormFlattening(),
        // then all fields are flattened. Otherwise only the included fields are flattened.
        form.flattenFields();
    }
}


FillFlattenMerge1 C#

C#
using System;
using System.Collections.Generic;
using System.IO;
using iText.Commons.Utils;
using iText.Forms;
using iText.Forms.Fields;
using iText.IO.Source;
using iText.Kernel.Pdf;

namespace iText.Samples.Sandbox.Acroforms.Reporting
{
    public class FillFlattenMerge1
    {
        public static readonly String DEST = "results/sandbox/acroforms/reporting/fill_flatten_merge1.pdf";

        public static readonly String DATA = "../../../resources/data/united_states.csv";
        public static readonly String SRC = "../../../resources/pdfs/state.pdf";

        public static void Main(String[] args)
        {
            FileInfo file = new FileInfo(DEST);
            file.Directory.Create();

            new FillFlattenMerge1().ManipulatePdf(DEST);
        }

        protected void ManipulatePdf(String dest)
        {
            PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
            PdfPageFormCopier formCopier = new PdfPageFormCopier();

            // Initialize an outline tree of the document and sets outline mode to true
            pdfDoc.InitializeOutlines();

            using (StreamReader streamReader = new StreamReader(DATA))
            {
                // Read first line with headers,
                // do nothing with this line, because headers are already filled in form
                String line = streamReader.ReadLine();

                while ((line = streamReader.ReadLine()) != null)
                {
                    // Create a PDF in memory
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    PdfDocument pdfInnerDoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(baos));
                    PdfAcroForm form = PdfFormCreator.GetAcroForm(pdfInnerDoc, true);

                    // Parse text line and fill all fields of form
                    FillAndFlattenForm(line, form);
                    pdfInnerDoc.Close();

                    // Copy page with current filled form to the result pdf document
                    pdfInnerDoc = new PdfDocument(new PdfReader(new MemoryStream(baos.ToArray())));
                    pdfInnerDoc.CopyPagesTo(1, pdfInnerDoc.GetNumberOfPages(), pdfDoc, formCopier);
                    pdfInnerDoc.Close();
                }
            }

            pdfDoc.Close();
        }

        public void FillAndFlattenForm(String line, PdfAcroForm form)
        {
            StringTokenizer tokenizer = new StringTokenizer(line, ";");
            IDictionary<String, PdfFormField> fields = form.GetAllFormFields();

            fields["name"].SetValue(tokenizer.NextToken());
            fields["abbr"].SetValue(tokenizer.NextToken());
            fields["capital"].SetValue(tokenizer.NextToken());
            fields["city"].SetValue(tokenizer.NextToken());
            fields["population"].SetValue(tokenizer.NextToken());
            fields["surface"].SetValue(tokenizer.NextToken());
            fields["timezone1"].SetValue(tokenizer.NextToken());
            fields["timezone2"].SetValue(tokenizer.NextToken());
            fields["dst"].SetValue(tokenizer.NextToken());

            // If no fields have been explicitly included via partialFormFlattening(),
            // then all fields are flattened. Otherwise only the included fields are flattened.
            form.FlattenFields();
        }
    }
}

fillflattenmerge2

JAVA
/*
    This file is part of the iText (R) project.
    Copyright (c) 1998-2023 Apryse Group NV
    Authors: Apryse Software.

    For more information, please contact iText Software at this address:
    sales@itextpdf.com
 */
package com.itextpdf.samples.sandbox.acroforms.reporting;

import com.itextpdf.forms.PdfAcroForm;
import com.itextpdf.forms.PdfPageFormCopier;
import com.itextpdf.forms.fields.PdfFormCreator;
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 java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileReader;
import java.util.Map;
import java.util.StringTokenizer;

public class FillFlattenMerge2 {
    public static final String DEST = "./target/sandbox/acroforms/reporting/fill_flatten_merge2.pdf";

    public static final String DATA = "./src/main/resources/data/united_states.csv";
    public static final String SRC = "./src/main/resources/pdfs/state.pdf";

    public static void main(String[] args) throws Exception {
        File file = new File(DEST);
        file.getParentFile().mkdirs();

        new FillFlattenMerge2().manipulatePdf(DEST);
    }

    protected void manipulatePdf(String dest) throws Exception {
        PdfWriter writer = new PdfWriter(dest);
        PdfPageFormCopier formCopier = new PdfPageFormCopier();

        // In smart mode when resources (such as fonts, images,...) are encountered,
        // a reference to these resources is saved in a cache and can be reused.
        // This mode reduces the file size of the resulting PDF document.
        writer.setSmartMode(true);
        PdfDocument pdfDoc = new PdfDocument(writer);

        // Initialize an outline tree of the document and sets outline mode to true
        pdfDoc.initializeOutlines();

        try (BufferedReader br = new BufferedReader(new FileReader(DATA))) {

            // Read first line with headers,
            // do nothing with this line, because headers are already filled in form
            String line = br.readLine();

            while ((line = br.readLine()) != null) {

                // Сreate a PDF in memory
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                PdfDocument pdfInnerDoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(baos));
                PdfAcroForm form = PdfFormCreator.getAcroForm(pdfInnerDoc, true);

                // Parse text line and fill all fields of form
                fillAndFlattenForm(line, form);
                pdfInnerDoc.close();

                // Copy page with current filled form to the result pdf document
                pdfInnerDoc = new PdfDocument(new PdfReader(new ByteArrayInputStream(baos.toByteArray())));
                pdfInnerDoc.copyPagesTo(1, pdfInnerDoc.getNumberOfPages(), pdfDoc, formCopier);
                pdfInnerDoc.close();
            }
        }

        pdfDoc.close();
    }

    public void fillAndFlattenForm(String line, PdfAcroForm form) {
        StringTokenizer tokenizer = new StringTokenizer(line, ";");
        Map<String, PdfFormField> fields = form.getAllFormFields();

        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());

        // If no fields have been explicitly included via partialFormFlattening(),
        // then all fields are flattened. Otherwise only the included fields are flattened.
        form.flattenFields();
    }
}


FillFlattenMerge2 C#

C#
using System;
using System.Collections.Generic;
using System.IO;
using iText.Commons.Utils;
using iText.Forms;
using iText.Forms.Fields;
using iText.IO.Source;
using iText.Kernel.Pdf;

namespace iText.Samples.Sandbox.Acroforms.Reporting
{
    public class FillFlattenMerge2
    {
        public static readonly String DEST = "results/sandbox/acroforms/reporting/fill_flatten_merge2.pdf";

        public static readonly String DATA = "../../../resources/data/united_states.csv";
        public static readonly String SRC = "../../../resources/pdfs/state.pdf";

        public static void Main(String[] args)
        {
            FileInfo file = new FileInfo(DEST);
            file.Directory.Create();

            new FillFlattenMerge2().ManipulatePdf(DEST);
        }

        protected void ManipulatePdf(String dest)
        {
            PdfWriter writer = new PdfWriter(dest);
            PdfPageFormCopier formCopier = new PdfPageFormCopier();

            // In smart mode when resources (such as fonts, images,...) are encountered,
            // a reference to these resources is saved in a cache and can be reused.
            // This mode reduces the file size of the resulting PDF document.
            writer.SetSmartMode(true);
            PdfDocument pdfDoc = new PdfDocument(writer);

            // Initialize an outline tree of the document and sets outline mode to true
            pdfDoc.InitializeOutlines();

            using (StreamReader streamReader = new StreamReader(DATA))
            {
                // Read first line with headers,
                // do nothing with this line, because headers are already filled in form
                String line = streamReader.ReadLine();

                while ((line = streamReader.ReadLine()) != null)
                {
                    // Сreate a PDF in memory
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    PdfDocument pdfInnerDoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(baos));
                    PdfAcroForm form = PdfFormCreator.GetAcroForm(pdfInnerDoc, true);

                    // Parse text line and fill all fields of form
                    FillAndFlattenForm(line, form);
                    pdfInnerDoc.Close();

                    // Copy page with current filled form to the result pdf document
                    pdfInnerDoc = new PdfDocument(new PdfReader(new MemoryStream(baos.ToArray())));
                    pdfInnerDoc.CopyPagesTo(1, pdfInnerDoc.GetNumberOfPages(), pdfDoc, formCopier);
                    pdfInnerDoc.Close();
                }
            }

            pdfDoc.Close();
        }

        public void FillAndFlattenForm(String line, PdfAcroForm form)
        {
            StringTokenizer tokenizer = new StringTokenizer(line, ";");
            IDictionary<String, PdfFormField> fields = form.GetAllFormFields();

            fields["name"].SetValue(tokenizer.NextToken());
            fields["abbr"].SetValue(tokenizer.NextToken());
            fields["capital"].SetValue(tokenizer.NextToken());
            fields["city"].SetValue(tokenizer.NextToken());
            fields["population"].SetValue(tokenizer.NextToken());
            fields["surface"].SetValue(tokenizer.NextToken());
            fields["timezone1"].SetValue(tokenizer.NextToken());
            fields["timezone2"].SetValue(tokenizer.NextToken());
            fields["dst"].SetValue(tokenizer.NextToken());

            // If no fields have been explicitly included via partialFormFlattening(),
            // then all fields are flattened. Otherwise only the included fields are flattened.
            form.FlattenFields();
        }
    }
}

fillflattenmerge3

JAVA
/*
    This file is part of the iText (R) project.
    Copyright (c) 1998-2023 Apryse Group NV
    Authors: Apryse Software.

    For more information, please contact iText Software at this address:
    sales@itextpdf.com
 */
package com.itextpdf.samples.sandbox.acroforms.reporting;

import com.itextpdf.forms.PdfAcroForm;
import com.itextpdf.forms.fields.PdfFormCreator;
import com.itextpdf.forms.fields.PdfFormField;
import com.itextpdf.io.font.constants.StandardFonts;
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.properties.TextAlignment;
import com.itextpdf.layout.properties.VerticalAlignment;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;

public class FillFlattenMerge3 {
    public static final String DEST = "./target/sandbox/acroforms/reporting/fill_flatten_merge3.pdf";

    public static final String DATA = "./src/main/resources/data/united_states.csv";
    public static final String SRC = "./src/main/resources/pdfs/state.pdf";

    public static final String[] FIELDS = {
            "name", "abbr", "capital", "city", "population", "surface", "timezone1", "timezone2", "dst"
    };

    public static void main(String[] args) throws Exception {
        File file = new File(DEST);
        file.getParentFile().mkdirs();

        new FillFlattenMerge3().manipulatePdf(DEST);
    }

    protected void manipulatePdf(String dest) throws Exception {
        PdfDocument srcDoc = new PdfDocument(new PdfReader(SRC));
        PdfAcroForm form = PdfFormCreator.getAcroForm(srcDoc, true);

        // Create a map with fields from the acroform and their names
        Map<String, Rectangle> positions = new HashMap<>();
        Map<String, PdfFormField> fields = form.getAllFormFields();
        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(StandardFonts.HELVETICA);

        // Event handler copies content of the source pdf file on every page
        // of the result pdf file as template to fill in.
        pdfDoc.addEventHandler(PdfDocumentEvent.END_PAGE,
                new PaginationEventHandler(srcDoc.getFirstPage().copyAsFormXObject(pdfDoc)));
        srcDoc.close();

        try (BufferedReader br = new BufferedReader(new FileReader(DATA))) {

            // Read first line with headers,
            // do nothing with current text line, because headers are already filled in form
            String line = br.readLine();

            while ((line = br.readLine()) != null) {
                int i = 0;
                StringTokenizer tokenizer = new StringTokenizer(line, ";");

                pdfDoc.addNewPage();

                while (tokenizer.hasMoreTokens()) {

                    // Fill in current form field, got by the name from FIELDS[],
                    // with content, read from the current token
                    process(doc, FIELDS[i++], tokenizer.nextToken(), font, positions);
                }
            }
        }

        doc.close();
    }

    protected void process(Document doc, String name, String value, PdfFont font, Map<String, Rectangle> positions) {
        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) {
            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)
                    .addXObjectAt(background, 0, 0);

            // Add the page number
            new Canvas(canvas, ((PdfDocumentEvent) event).getPage().getPageSize())
                    .showTextAligned("page " + pageNum, 550, 800, TextAlignment.RIGHT);
        }
    }
}


FillFlattenMerge3 C#

C#
using System;
using System.Collections.Generic;
using System.IO;
using iText.Commons.Utils;
using iText.Forms;
using iText.Forms.Fields;
using iText.IO.Font.Constants;
using iText.Kernel.Events;
using iText.Kernel.Font;
using iText.Kernel.Geom;
using iText.Kernel.Pdf;
using iText.Kernel.Pdf.Canvas;
using iText.Kernel.Pdf.Xobject;
using iText.Layout;
using iText.Layout.Element;
using iText.Layout.Properties;

namespace iText.Samples.Sandbox.Acroforms.Reporting
{
    public class FillFlattenMerge3
    {
        public static readonly String DEST = "results/sandbox/acroforms/reporting/fill_flatten_merge3.pdf";

        public static readonly String DATA = "../../../resources/data/united_states.csv";
        public static readonly String SRC = "../../../resources/pdfs/state.pdf";

        public static readonly String[] FIELDS =
        {
            "name", "abbr", "capital", "city", "population", "surface", "timezone1", "timezone2", "dst"
        };

        public static void Main(String[] args)
        {
            FileInfo file = new FileInfo(DEST);
            file.Directory.Create();

            new FillFlattenMerge3().ManipulatePdf(DEST);
        }

        protected void ManipulatePdf(String dest)
        {
            PdfDocument srcDoc = new PdfDocument(new PdfReader(SRC));
            PdfAcroForm form = PdfFormCreator.GetAcroForm(srcDoc, true);

            // Create a map with fields from the acroform and their names
            Dictionary<String, Rectangle> positions = new Dictionary<String, Rectangle>();
            IDictionary<String, PdfFormField> fields = form.GetAllFormFields();
            foreach (PdfFormField field in fields.Values)
            {
                positions.Add(field.GetFieldName().GetValue(), field.GetWidgets()[0].GetRectangle().ToRectangle());
            }

            PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
            Document doc = new Document(pdfDoc);
            PdfFont font = PdfFontFactory.CreateFont(StandardFonts.HELVETICA);

            // Event handler copies content of the source pdf file on every page
            // of the result pdf file as template to fill in.
            pdfDoc.AddEventHandler(PdfDocumentEvent.END_PAGE,
                new PaginationEventHandler(srcDoc.GetFirstPage().CopyAsFormXObject(pdfDoc)));
            srcDoc.Close();

            using (StreamReader streamReader = new StreamReader(DATA))
            {
                // Read first line with headers,
                // do nothing with current text line, because headers are already filled in form
                String line = streamReader.ReadLine();

                while ((line = streamReader.ReadLine()) != null)
                {
                    int i = 0;
                    StringTokenizer tokenizer = new StringTokenizer(line, ";");

                    pdfDoc.AddNewPage();

                    while (tokenizer.HasMoreTokens())
                    {
                        // Fill in current form field, got by the name from FIELDS[],
                        // with content, read from the current token
                        Process(doc, FIELDS[i++], tokenizer.NextToken(), font, positions);
                    }
                }
            }

            doc.Close();
        }

        protected void Process(Document doc, String name, String value, PdfFont font,
            Dictionary<String, Rectangle> positions)
        {
            Rectangle rect = positions[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 : IEventHandler
        {
            PdfFormXObject background;

            public PaginationEventHandler(PdfFormXObject background)
            {
                this.background = background;
            }

            public void HandleEvent(Event currentEvent)
            {
                PdfDocument pdfDoc = ((PdfDocumentEvent) currentEvent).GetDocument();
                int pageNum = pdfDoc.GetPageNumber(((PdfDocumentEvent) currentEvent).GetPage());

                // Add the background
                PdfCanvas canvas = new PdfCanvas(pdfDoc.GetPage(pageNum).NewContentStreamBefore(),
                        ((PdfDocumentEvent) currentEvent).GetPage().GetResources(), pdfDoc)
                    .AddXObjectAt(background, 0, 0);

                // Add the page number
                new Canvas(canvas, ((PdfDocumentEvent) currentEvent).GetPage().GetPageSize())
                    .ShowTextAligned("page " + pageNum, 550, 800, TextAlignment.RIGHT);
            }
        }
    }
}

fillform

JAVA
/*
    This file is part of the iText (R) project.
    Copyright (c) 1998-2023 Apryse Group NV
    Authors: Apryse Software.

    For more information, please contact iText Software at this address:
    sales@itextpdf.com
 */
package com.itextpdf.samples.sandbox.acroforms.reporting;

import com.itextpdf.forms.PdfAcroForm;
import com.itextpdf.forms.fields.PdfFormCreator;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;

import java.io.File;

public class FillForm {
    public static final String DEST = "./target/sandbox/acroforms/reporting/fill_form.pdf";

    public static final String SRC = "./src/main/resources/pdfs/state.pdf";

    public static void main(String[] args) throws Exception {
        File file = new File(DEST);
        file.getParentFile().mkdirs();

        new FillForm().manipulatePdf(DEST);
    }

    protected void manipulatePdf(String dest) throws Exception {
        PdfDocument pdfDoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(dest));
        PdfAcroForm form = PdfFormCreator.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();
    }
}


fillform c#

C#
using System;
using System.IO;
using iText.Forms;
using iText.Forms.Fields;
using iText.Kernel.Pdf;

namespace iText.Samples.Sandbox.Acroforms.Reporting
{
    public class FillForm
    {
        public static readonly String DEST = "results/sandbox/acroforms/reporting/fill_form.pdf";

        public static readonly String SRC = "../../../resources/pdfs/state.pdf";

        public static void Main(String[] args)
        {
            FileInfo file = new FileInfo(DEST);
            file.Directory.Create();

            new FillForm().ManipulatePdf(DEST);
        }

        protected void ManipulatePdf(String dest)
        {
            PdfDocument pdfDoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(dest));
            PdfAcroForm form = PdfFormCreator.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();
        }
    }
}


flattenform

JAVA
/*
    This file is part of the iText (R) project.
    Copyright (c) 1998-2023 Apryse Group NV
    Authors: Apryse Software.

    For more information, please contact iText Software at this address:
    sales@itextpdf.com
 */
package com.itextpdf.samples.sandbox.acroforms.reporting;

import com.itextpdf.forms.PdfAcroForm;
import com.itextpdf.forms.fields.PdfFormCreator;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;

import java.io.File;

public class FlattenForm {
    public static final String DEST = "./target/sandbox/acroforms/reporting/flatten_form.pdf";

    public static final String SRC = "./src/main/resources/pdfs/state.pdf";

    public static void main(String[] args) throws Exception {
        File file = new File(DEST);
        file.getParentFile().mkdirs();

        new FlattenForm().manipulatePdf(DEST);
    }

    protected void manipulatePdf(String dest) throws Exception {
        PdfDocument pdfDoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(dest));
        PdfAcroForm form = PdfFormCreator.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");

        // If no fields have been explicitly included via partialFormFlattening(),
        // then all fields are flattened. Otherwise only the included fields are flattened.
        form.flattenFields();

        pdfDoc.close();
    }
}

FlattenForm C#

C#
using System;
using System.IO;
using iText.Forms;
using iText.Forms.Fields;
using iText.Kernel.Pdf;

namespace iText.Samples.Sandbox.Acroforms.Reporting
{
    public class FlattenForm
    {
        public static readonly String DEST = "results/sandbox/acroforms/reporting/flatten_form.pdf";

        public static readonly String SRC = "../../../resources/pdfs/state.pdf";

        public static void Main(String[] args)
        {
            FileInfo file = new FileInfo(DEST);
            file.Directory.Create();

            new FlattenForm().ManipulatePdf(DEST);
        }

        protected void ManipulatePdf(String dest)
        {
            PdfDocument pdfDoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(dest));
            PdfAcroForm form = PdfFormCreator.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");

            // If no fields have been explicitly included via PartialFormFlattening(),
            // then all fields are flattened. Otherwise only the included fields are flattened.
            form.FlattenFields();

            pdfDoc.Close();
        }
    }
}

Resources

JavaScript errors detected

Please note, these errors can depend on your browser setup.

If this problem persists, please contact our support.