Flatten PDF form

PDF forms
7/8/2014

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.

C# code sample

1 // open 'U.S. Individual Income Tax Return' form 2 using (FileStream fileIn = new FileStream("f1040a.pdf", FileMode.Open, FileAccess.Read)) 3 { 4 Document form = new Document(fileIn); 5 6 // activate the javascript engine, so format actions will be executed. 7 form.ScriptBehavior = ScriptBehavior.Format; 8 9 // flatten all form-data with the current value, except text-field field-name. 10 foreach(Field field in form.Fields) 11 { 12 TextField textField = field as TextField; 13 if (textField != null) 14 { 15 textField.Value = textField.FullName; 16 } 17 18 foreach( Widget widget in field.Widgets ) 19 { 20 widget.Persistency = WidgetPersistency.Flatten; 21 } 22 } 23 24 // write flattened form back to disk 25 using (FileStream fileOut = new FileStream("flattenform.pdf", FileMode.Create, FileAccess.Write)) 26 { 27 form.Write(fileOut); 28 } 29 }

VB.NET code sample

1 // open 'U.S. Individual Income Tax Return' form 2 Using fileIn As New FileStream("..\..\..\inputDocuments\f1040a.pdf", FileMode.Open, FileAccess.Read) 3 Dim form As New Document(fileIn) 4 5 'Activate the javascript engine, so format actions will be executed. 6 form.ScriptBehavior = ScriptBehavior.Format 7 8 'Flatten all form-data with the current value, except text-field field-name. 9 For Each field As Field In form.Fields 10 Dim textField As TextField = TryCast(field, TextField) 11 If textField IsNot Nothing Then 12 textField.Value = textField.FullName 13 End If 14 15 For Each widget As Widget In field.Widgets 16 widget.Persistency = WidgetPersistency.Flatten 17 Next 18 Next 19 20 ' write flattened form back to disk 21 Using fileOut As New FileStream("..\..\flattenform.pdf", FileMode.Create, FileAccess.Write) 22 form.Write(fileOut) 23 End Using 24 End Using

The original PDF form:

flatten-PDF-old.png

The flattened PDF form:

flatten-PDF-new.png