Flatten PDF form

This code sample shows how to fill out a form and then flatten it. Flattening means that the fields are taken out and the field values are added as static graphics. After flattening, the user can no longer interact with the form fields.

// open 'U.S. Individual Income Tax Return' form
using (FileStream fileIn = new FileStream("f1040a.pdf", FileMode.Open, FileAccess.Read))
{
   Document form = new Document(fileIn);

   // activate the javascript engine, so format actions will be executed.
   form.ScriptBehavior = ScriptBehavior.Format;

   // flatten all form-data with the current value, except text-field field-name.
   foreach(Field field in form.Fields)
   {
      TextField textField = field as TextField;
      if (textField != null)
      {
         textField.Value = textField.FullName;
      }

      foreach( Widget widget in field.Widgets )
      {
         widget.Persistency = WidgetPersistency.Flatten;
      }
   }

   // write flattened form back to disk
   using (FileStream fileOut = new FileStream("flattenform.pdf", FileMode.Create, FileAccess.Write))
   {
      form.Write(fileOut);
   }
}
// open 'U.S. Individual Income Tax Return' form
Using fileIn As New FileStream("..\..\..\inputDocuments\f1040a.pdf", FileMode.Open, FileAccess.Read)
            Dim form As New Document(fileIn)

            'Activate the javascript engine, so format actions will be executed.
            form.ScriptBehavior = ScriptBehavior.Format

            'Flatten all form-data with the current value, except text-field field-name.
            For Each field As Field In form.Fields
                Dim textField As TextField = TryCast(field, TextField)
                If textField IsNot Nothing Then
                    textField.Value = textField.FullName
                End If

                For Each widget As Widget In field.Widgets
                    widget.Persistency = WidgetPersistency.Flatten
                Next
            Next

            ' write flattened form back to disk
            Using fileOut As New FileStream("..\..\flattenform.pdf", FileMode.Create, FileAccess.Write)
                form.Write(fileOut)
            End Using
        End Using

The original PDF form:

Flatten PDF Old

The flattened PDF form:

Flatten PDF New