DEV Community

Cover image for How to Fill Interactive PDF Forms in C# (Text Fields, Checkboxes, Dropdowns, and More)
Dheeraj Malik
Dheeraj Malik

Posted on Edited on

How to Fill Interactive PDF Forms in C# (Text Fields, Checkboxes, Dropdowns, and More)

When building employee registration systems, application workflows, or document management tools, you may need to fill existing PDF forms with data from a database or user submission.

If a PDF contains interactive form fields (AcroForm), you can populate them directly in C# without manually positioning text on the page. This includes entering text, checking boxes, selecting radio buttons, and choosing items from dropdowns or list boxes.

In this tutorial, we'll use an employee registration form to demonstrate how to access and fill different types of PDF form fields in C#.

Prerequisites

Before getting started, install the required PDF processing library in your C# project.

In Visual Studio, go to Tools > NuGet Package Manager > Package Manager Console, and run:

Install-Package FreeSpire.PDF -Version 12.4.0
Enter fullscreen mode Exit fullscreen mode

Alternatively, you can install the package using the .NET CLI:

dotnet add package FreeSpire.PDF --version 12.4.0
Enter fullscreen mode Exit fullscreen mode

Fill Interactive PDF Form Fields in Csharp

Suppose we have a PDF file named Employee_Registration_Form.pdf containing the following fields:

Field Type Value to Enter
Full Name Text box Emma Wilson
Address Text box Seattle, Washington
Gender Radio button Female
Accept Terms Checkbox Checked
Department Dropdown Engineering
Interests List box Photography

We'll load the PDF, identify each field by its internal name, assign the appropriate value, and save the completed form.

Step 1: Import the Required Namespaces

Start by importing the namespaces used to work with PDF documents and interactive form fields.

using System;
using Spire.Pdf;
using Spire.Pdf.Fields;
using Spire.Pdf.Widget;
Enter fullscreen mode Exit fullscreen mode

Step 2: Load the PDF and Access Its Form Fields

Use PdfDocument.LoadFromFile() to open the PDF template. Then retrieve the interactive form and its field collection.

// Load the PDF form
PdfDocument pdf = new PdfDocument();
pdf.LoadFromFile("Employee_Registration_Form.pdf");

// Access the interactive form
PdfFormWidget form = pdf.Form as PdfFormWidget;

// Get the form field collection
PdfFormFieldWidgetCollection fields = form.FieldsWidget;
Enter fullscreen mode Exit fullscreen mode

The FieldsWidget collection allows you to access existing fields by index.

One thing to keep in mind: the label displayed beside a field may not match its internal name.

For example, a field labeled "Full Name" might internally be named full_name, Text1, or something else.

The code must use the actual field names stored in the PDF, rather than the visible labels. You can inspect those names before filling the form if you're working with an unfamiliar template.

The snippet above assumes the PDF contains an AcroForm. The complete example includes a check for missing form fields.

Step 3: Identify and Fill Each Field

Different form controls use different properties to store their values.

Form Field Type Property Example
Text box Text textBox.Text = "Emma Wilson";
Radio button SelectedIndex radio.SelectedIndex = 1;
Checkbox Checked checkBox.Checked = true;
Dropdown SelectedIndex comboBox.SelectedIndex = new int[] { 1 };
List box SelectedIndex listBox.SelectedIndex = new int[] { 0 };

For instance, to populate the full_name text field:

for (int i = 0; i < fields.Count; i++)
{
    PdfField field = fields[i];

    if (field is PdfTextBoxFieldWidget textBox &&
        field.Name == "full_name")
    {
        textBox.Text = "Emma Wilson";
    }
}
Enter fullscreen mode Exit fullscreen mode

The code first checks whether the current field is a text box, then matches its name before assigning the value.

For choice-based controls, there are two details worth remembering:

  • Indexes are zero-based. Setting SelectedIndex = 1 selects the second option.
  • The property types differ. Radio buttons accept an integer index, while dropdowns and list boxes use an integer array.

Make sure the selected indexes correspond to the intended options in your PDF template.

Step 4: Save the Completed PDF

After updating the form fields, save the document to a new file.

// Save the completed form
pdf.SaveToFile("Employee_Registration_Completed.pdf", FileFormat.PDF);

// Close the document
pdf.Close();
Enter fullscreen mode Exit fullscreen mode

Using a separate output filename keeps the original template available for future use.

The saved PDF still contains interactive form fields, so its values can be changed later in a compatible PDF viewer.

Complete C# Example: Fill Multiple PDF Form Fields

The following program fills text boxes, a radio button group, a checkbox, a dropdown, and a list box in a single pass.

For this example, assume the PDF has the following internal field names:

  • full_name and address for text boxes
  • gender for a radio button group, with Male and Female as the first two options
  • accept_terms for a checkbox
  • department for a dropdown, with Engineering as the second option
  • interests for a list box, with Photography as the first option
using System;
using Spire.Pdf;
using Spire.Pdf.Fields;
using Spire.Pdf.Widget;

class Program
{
    static void Main()
    {
        PdfDocument pdf = new PdfDocument();

        try
        {
            // Load the PDF form
            pdf.LoadFromFile("Employee_Registration_Form.pdf");

            // Get the interactive form
            PdfFormWidget form = pdf.Form as PdfFormWidget;

            if (form == null || form.FieldsWidget.Count == 0)
            {
                Console.WriteLine("No fillable AcroForm fields found.");
                return;
            }

            PdfFormFieldWidgetCollection fields = form.FieldsWidget;

            // Loop through the form fields
            for (int i = 0; i < fields.Count; i++)
            {
                PdfField field = fields[i];

                // Fill text fields
                if (field is PdfTextBoxFieldWidget textBox)
                {
                    switch (field.Name)
                    {
                        case "full_name":
                            textBox.Text = "Emma Wilson";
                            break;

                        case "address":
                            textBox.Text = "Seattle, Washington";
                            break;
                    }
                }

                // Select a radio button
                else if (field is PdfRadioButtonListFieldWidget radio)
                {
                    if (field.Name == "gender")
                    {
                        // Select Female (second option)
                        radio.SelectedIndex = 1;
                    }
                }

                // Check a checkbox
                else if (field is PdfCheckBoxWidgetFieldWidget checkBox)
                {
                    if (field.Name == "accept_terms")
                    {
                        checkBox.Checked = true;
                    }
                }

                // Select an item from a dropdown
                else if (field is PdfComboBoxWidgetFieldWidget comboBox)
                {
                    if (field.Name == "department")
                    {
                        // Select Engineering (second option)
                        comboBox.SelectedIndex = new int[] { 1 };
                    }
                }

                // Select an item from a list box
                else if (field is PdfListBoxWidgetFieldWidget listBox)
                {
                    if (field.Name == "interests")
                    {
                        // Select Photography (first option)
                        listBox.SelectedIndex = new int[] { 0 };
                    }
                }
            }

            // Save the filled PDF
            pdf.SaveToFile(
                "Employee_Registration_Completed.pdf",
                FileFormat.PDF
            );

            Console.WriteLine("PDF form filled successfully.");
        }
        finally
        {
            pdf.Close();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

After running the program, the completed form is saved as Employee_Registration_Completed.pdf.

The example assumes that the PDF contains the specified field names and that the choice fields have the expected option order. When using your own template, adjust those values accordingly.

Common Issues When Filling PDF Forms in Csharp

1. The Code Runs, but No Fields Are Filled

This often happens when the field names in the code do not match the names stored in the PDF.

You can print all available field names and types to check:

for (int i = 0; i < fields.Count; i++)
{
    PdfField field = fields[i];

    Console.WriteLine(
        $"{field.Name} - {field.GetType().Name}"
    );
}
Enter fullscreen mode Exit fullscreen mode

Compare the output with the names used in your code. Field-name matching is case-sensitive, so even small differences can prevent values from being assigned.

2. Text Is Missing or Displays Incorrectly

A form field may use a font that doesn't support the characters you're trying to insert.

This is particularly common when filling multilingual forms that contain Chinese, Japanese, or other non-Latin characters.

In such cases, assign a compatible font to the text field before setting its value:

// Requires: using Spire.Pdf.Graphics;
// Requires a compatible font installed on the system

textBox.Font = new PdfTrueTypeFont(
    new System.Drawing.Font("Arial Unicode MS", 11),
    true
);

textBox.Text = "Sample Text";
Enter fullscreen mode Exit fullscreen mode

The font must be available on the machine running the program. For multilingual content, replace the sample text with the required characters and verify that the installed font supports them.

If the issue persists, check the field's appearance settings and open the output in a different PDF viewer to rule out rendering differences.

3. The Wrong Radio Button or Dropdown Option Is Selected

The likely cause is an incorrect option index.

For example:

radio.SelectedIndex = 1;
Enter fullscreen mode Exit fullscreen mode

This selects the second radio button in the group, not necessarily the option labeled "Female."

The actual option order depends on how the PDF form was created. Check the template before assigning indexes, especially when forms come from different sources.

4. The PDF Has Visible Input Areas, but No Form Fields Are Found

Not every PDF that looks like a form contains interactive fields.

A PDF may have blank lines and boxes drawn on the page without any AcroForm structure. Scanned forms and previously flattened PDFs also fall into this category.

Some documents use XFA forms, which require different handling.

If the field collection is empty, inspect the PDF's underlying form structure before attempting to populate it with AcroForm APIs.

Conclusion

Filling an interactive PDF in C# involves accessing the existing form fields, identifying their types, assigning the appropriate values, and saving the updated document.

This approach can be used in employee onboarding, application processing, and other workflows that rely on predefined PDF templates. By replacing the hardcoded values with data from a database or user submission, you can automate repetitive form-filling tasks while keeping the original PDF layout intact.

Top comments (0)