Skip to content

Miscellaneous

PDF form fields flattening

PDF form fields are objects separated from regular page content, they sit on top of existing page content. Because they are not part of page content, operations that involve working on the page content do not consider them. For these scenarios a common requirement is to merge the field content with the regular page content. This operation is called form fields flattening.
PDF4NET supports form fields flattening at form level

C#
// The call below flattens all form fields in a PDF form
document.Form.FlattenFields();

at field level

C#
// The code below flattens the textBoxField object (all its widgets)
document.Form.FlattenField(textBoxField);

and at field widget level.

C#
// The call below flattens only the specified widget
field.Widgets[index].Flatten();

The field flattening operation is a destructive operation, the field visual appearance is included in the page content and the complete field metadata is removed from the PDF file.
PDF4NET also includes support to flatten form fields on the fly when extracting page content from existing files:

C#
1
2
3
// The call below extracts the page content as vector image. 
// The form fields are flatened so that their content is extracted with the page content.
PDFPageContent pc = pdfFile.ExtractPageContent(index, true, true);

How to merge identical PDF forms but with different data

A common requirement is to merge multiple PDF form that are identical as structure, but each one containing different data.
Because the PDF forms have identical structure, when they are merged, the fields are also merged (fields with the same name appear in each PDF form) and the final document keeps the data only from the first form used in the merge process, and this data is propagated to all the other forms.
In order to avoid this to happen, you have 2 options:

  1. Flatten the PDF forms before merging. In this way the field content is merged with page content and there is no collision between fields with the same name from different forms. The drawback is that the final file is no longer editable and the form data can no longer be extracted or exported.
    Please see below a possible implementation of this solution:

    C#
    1
    2
    3
    4
    5
    6
    7
       PDFFixedDocument document = new PDFFixedDocument();
       for (int i = 0; i < formsToMerge.Length; i++)
       {
           document.AppendFile(formsToMerge[i]);
           document.Form.FlattenFields();
       }
       document.Save("merged-form.pdf");
    

  2. Rename the form fields before merging. This solution renames the form fields in each form to a unique name (current field name + the form index in the merge process, for example), thus there is no longer any collision between form fields in different forms.