Interactive Forms in PDF Documents
- 10 minutes to read
A PDF document can contain interactive forms (AcroForms) with fillable form fields (text fields, buttons, list boxes, and so on).
PDF Document API allows you to create, fill, flatten, and delete fillable PDF forms. You can import or export AcroForm data to various formats.
Create Interactive Form Fields
The table below lists available form fields and API used to create each type.
Form Field | Class | Method |
---|---|---|
Check Box | PdfAcroFormCheckBoxField | PdfAcroFormField.CreateCheckBox |
Combo box | PdfAcroFormComboBoxField | PdfAcroFormField.CreateComboBox |
Group | PdfAcroFormGroupField | PdfAcroFormField.CreateGroup |
List Box | PdfAcroFormListBoxField | PdfAcroFormField.CreateListBox |
Radio Group | PdfAcroFormRadioGroupField | PdfAcroFormField.CreateRadioGroup |
Signature | PdfAcroFormSignatureField | PdfAcroFormField.CreateSignature |
Text Box | PdfAcroFormTextBoxField | PdfAcroFormField.CreateTextBox |
This example shows how to create text box and radio button group fields and add them to a document.
using DevExpress.Pdf;
namespace AddFormFieldsToExistingDocument {
class Program {
static void Main(string[] args) {
using (PdfDocumentProcessor processor = new PdfDocumentProcessor())
{
// Load a document.
processor.LoadDocument("..\\..\\Document.pdf");
// Create a text box field specifying the field name, page number, and field location on the page.
PdfAcroFormTextBoxField textBox = new PdfAcroFormTextBoxField("text box", 1, new PdfRectangle(230, 690, 280, 710));
// Specify text box text, and appearance.
textBox.Text = "Text Box";
textBox.Appearance.BackgroundColor = new PdfRGBColor(0.8, 0.5, 0.3);
textBox.Appearance.FontSize = 12;
// Create a radio group field specifying its name and the page number.
PdfAcroFormRadioGroupField radioGroup = new PdfAcroFormRadioGroupField("Gender Group", 1);
// Add the first radio button to the group and specify its location using a PdfRectangle object.
radioGroup.AddButton("button1", new PdfRectangle(230, 635, 250, 655));
// Add the second radio button to the group.
radioGroup.AddButton("button2", new PdfRectangle(310, 635, 330, 655));
// Specify radio group selected index, and appearance.
radioGroup.SelectedIndex = 0;
radioGroup.Appearance.BorderAppearance = new PdfAcroFormBorderAppearance()
{ Color = new PdfRGBColor(0.8, 0.5, 0.3), Width = 3 };
// Add form fields to the page.
processor.AddFormFields(textBox, radioGroup);
// Save the result document.
processor.SaveDocument("..\\..\\Result.pdf");
}
}
}
}
Field Name Collisions
When you add a form field to the document, make sure that it’s name is unique. Otherwise, a conflict may occur.
Use API from the table below to prevent and resolve field name conflicts:
API | Description |
---|---|
PdfDocumentProcessor.CheckFormFieldNameCollisions | Checks whether the form field name already exists. |
PdfAcroFormFieldNameCollision.Field | Retrieves a conflicting form field. |
PdfAcroFormFieldNameCollision.ForbiddenNames | Gets the collection of forbidden names. |
The code sample below checks whether the created field names already exist in the loaded document and renames the conflicting field.
List<PdfAcroFormField> fields = new List<PdfAcroFormField>();
fields.Add(textBox);
fields.Add(radioGroup);
// Check whether new form fields' names already exist in the document
IList<PdfAcroFormFieldNameCollision> collisions =
processor.CheckFormFieldNameCollisions(fields);
if (collisions.Count == 0)
Console.WriteLine("No name conflicts are detected");
else
{
foreach (var collision in collisions)
{
// Rename conflicting field
Console.WriteLine("The specified form field name ({0}) already exist in the document. Renaming...",
collision.Field.Name);
while (collision.ForbiddenNames.Contains(collision.Field.Name))
collision.Field.Name = Guid.NewGuid().ToString();
}
}
// Add fields to the document
// and save the result
processor.AddFormFields(fields);
processor.SaveDocument("Result.pdf");
Obtain Form Field Location
Fill Interactive Form Fields
Interactive form fields can have the following values:
- Text field - string;
- Radio group and check box - name of the checked/unchecked item;
- Combo box - a string array;
- Complex field (field group)- a PdfFormData object.
Utilize the PdfDocumentProcessor.GetFormData method to retrieve the PdfFormData object that contains interactive form data. You can call the PdfDocumentProcessor.GetFormFieldNames method to retrieve a list of field names and iterate through the returned string collection.
Note
Obtain a new PdfFormData instance after one of the following operations: add new interactive form fields, flatten interactive form, merge documents with interactive forms, or delete pages with interactive form fields.
// Load a document with an interactive form.
using (PdfDocumentProcessor documentProcessor = new PdfDocumentProcessor()) {
documentProcessor.LoadDocument(filePath + fileName + ".pdf");
// Obtain interactive form data from a document.
PdfFormData formData = documentProcessor.GetFormData();
// Specify the value for FirstName and LastName text boxes.
formData["FirstName"].Value = "Janet";
formData["LastName"].Value = "Leverling";
// Specify the value for the Gender radio group.
formData["Gender"].Value = "Female";
// Specify the check box checked appearance name.
formData["Check"].Value = "Yes";
// Specify values for the Category list box.
formData["Category"].Value = new string[] { "Entertainment", "Meals", "Morale" };
// Obtain data from the Address form field and specify values for Address child form fields.
PdfFormData address = formData["Address"];
// Specify the value for the Country combo box.
address["Country"].Value = "United States";
// Specify the value for City and Address text boxes.
address["City"].Value = "California";
address["Address"].Value = "20 Maple Avenue";
// Apply data to the interactive form.
documentProcessor.ApplyFormData(formData);
// Save the modified document.
documentProcessor.SaveDocument(filePath + fileName + "_new.pdf");
btnFillFormData.Enabled = false;
btnLoadFilledPDF.Enabled = true;
}
Fill an Interactive Form from a Data File
You can fill the PdfFormData object from a file with interactive form data (FDF, XML, XFDF or TXT). Pass the data file name and format as the PdfFormData constructor parameter. PdfDocumentProcessor automatically detects the file type.
using (PdfDocumentProcessor processor = new PdfDocumentProcessor())
{
processor.LoadDocument(pathForPdf);
PdfFormData data = new PdfFormData(pathForData);
processor.ApplyFormData(data);
processor.SaveDocument(pathForPdf);
}
Flatten an Interactive Form
The flattening process removes form field interactive features, so the form field value is converted to regular content (text, images, shapes, and so on). The flattening process cannot be undone, so we recommend that you save the flattened document under a different name.
You can flatten an entire form or a specific form field.
Flatten a Form
Call the PdfDocumentProcessor.FlattenForm method to flatten an entire form. This method returns false if the document does not contain an interactive form to be flattened.
using (PdfDocumentProcessor processor = new PdfDocumentProcessor())
{
processor.LoadDocument("FormDemo.pdf");
if (processor.FlattenForm())
processor.SaveDocument("Result.pdf");
}
Flatten a Form Field
Utilize the PdfDocumentProcessor.FlattenFormField method to flatten a specific field. This method returns false if the form field was not found in the document.
The code sample below flattens the VisaNo form field:
using (PdfDocumentProcessor pdfDocumentProcessor = new PdfDocumentProcessor())
{
pdfDocumentProcessor.LoadDocument("Documents//FormDemo.pdf");
if (pdfDocumentProcessor.Document.AcroForm != null)
{
pdfDocumentProcessor.FlattenFormField("VisaNo");
}
pdfDocumentProcessor.SaveDocument("FormDemo_new.pdf");
}
Import and Export Interactive Form Data
You can import and export AcroForm data to the following formats: FDF, XFDF, XML, and TXT.
Import Interactive Form Data
Call the PdfDocumentProcessor.Import method to import interactive form data. The previous interactive form data is automatically removed from the document after the import.
The example below demonstrates how to import interactive form data from an XML file:
using DevExpress.Pdf;
using (PdfDocumentProcessor processor = new PdfDocumentProcessor())
{
// Load a PDF document with AcroForm data.
processor.LoadDocument("..\\..\\EmptyForm.pdf");
// Import AcroForm data from an XML file.
processor.Import("..\\..\\InteractiveForm.xml");
// Save the imported document.
processor.SaveDocument("..\\..\\InteractiveForm.pdf");
}
Export Interactive Form Data
Utilize one of the following methods to export interactive form field data:
- PdfDocumentProcessor.Export — Exports interactive form data to the specified stream using specified form data format.
- PdfFormData.Save — Saves the interactive form data to a stream using form data format.
Before interactive form data export, make sure that the interactive form contains fields with filled values.
using DevExpress.Pdf;
using (PdfDocumentProcessor processor = new PdfDocumentProcessor())
{
// Load a PDF document with AcroForm data.
processor.LoadDocument("..\\..\\InteractiveForm.pdf");
// Export AcroForm data to XML format.
processor.Export("..\\..\\InteractiveForm.xml", PdfFormDataFormat.Xml);
PdfFormData data = processor.GetFormData();
data.Save(pathForExportedData, PdfFormDataFormat.Fdf);
}
Remove Form Fields
The code sample below removes an interactive form field:
using (PdfDocumentProcessor processor = new PdfDocumentProcessor())
{
// Load a document with an interactive form.
processor.LoadDocument("..\\..\\InteractiveForm.pdf");
// Remove a form field:
if (processor.RemoveFormField("FirstName"))
// Save the document.
processor.SaveDocument("..\\..\\Result.pdf");
else
// Show a message if the form field is not found in a document.
Console.WriteLine("The form field was not removed. Make sure that the form field name is correct.");
}
The code sample below removes an entire AcroForm:
using (PdfDocumentProcessor processor = new PdfDocumentProcessor())
{
// Load a document with an interactive form:
processor.LoadDocument("..\\..\\InteractiveForm.pdf");
// Remove the AcroForm:
if (processor.RemoveForm())
// Save the document:
processor.SaveDocument("..\\..\\Result.pdf");
else
// Show a message if the interactive form is not found:
Console.WriteLine("The interactive form was not removed. Make sure the interactive form exists.");
}