Flatten PDF interactive form fields in C# and VB.NET

PDF interactive form flattening is the process of making a PDF document non-interactive by taking the appearance of form fields, incorporating their appearance into the static contents of the PDF page containing them, and finally removing the form fields.

The following example shows a PDF interactive form with PDF .Net.

Complete code

using System;
using SautinSoft.Pdf;
using System.IO;

class Program
{
	static void Main()
	{
		// This property is necessary only for licensed version.
		//SautinSoft.Pdf.Serial = "XXXXXXXXXXX";

		using (var document = PdfDocument.Load("FormFilled.pdf"))

		{
			// A flag specifying whether to construct appearance for all form fields in the document.
			bool needAppearances = document.Form.NeedAppearances;

			foreach (var field in document.Form.Fields)
			{
				// Do not flatten button fields.
				if (field.FieldType == PdfFieldType.Button)
				continue;

				// Construct appearance, if needed.
				if (needAppearances)
				field.Appearance.Refresh();

				// Get the field's appearance form.
				var fieldAppearance = field.Appearance.Get();

				// If the field doesn't have an appearance, skip it.
				if (fieldAppearance == null)
				continue;

				// Add a new content group to the field's page and
				// add new form content with the field's appearance form to the content group.
				// The content group is added so that transformation from the next statement is localized to the content group.
				var flattenedContent = field.Page.Content.Elements.AddGroup().Elements.AddForm(fieldAppearance);

				// Translate the form content to the same position on the page that the field is in.
				var fieldBounds = field.Bounds;
				flattenedContent.Transform = PdfMatrix.CreateTranslation(fieldBounds.Left, fieldBounds.Bottom);
			}

			// Remove all fields, thus making the document non-interactive,
			// since their appearance is now contained directly in the content of their pages.
			document.Form.Fields.Clear();

			document.Save("FormFlattened.pdf");
		}
	}
}

            

Download.


If you need a new code example or have a question: email us at support@sautinsoft.com or ask at Online Chat (right-bottom corner of this page) or use the Form below:



Questions and suggestions from you are always welcome!

We are developing .Net components since 2002. We know PDF, DOCX, RTF, HTML, XLSX and Images formats. If you need any assistance with creating, modifying or converting documents in various formats, we can help you. We will write any code example for you absolutely free.