DEV Community

IronSoftware
IronSoftware

Posted on

Edit PDF Forms in C# (.NET Guide)

Our HR department was manually filling 200+ onboarding forms per month. Name, address, start date, benefits selections—all entered by hand into PDFs. It took hours and introduced typos that delayed compliance paperwork.

I automated the entire process in C#. Now we pull employee data from our database, fill the forms programmatically, and generate completed PDFs in seconds. Here's how.

What Are PDF Forms?

PDF forms (also called AcroForms) are interactive fields embedded in PDF documents: text boxes, checkboxes, dropdowns, radio buttons. Users fill them in Adobe Acrobat or browser PDF viewers, then save or submit the completed form.

using IronPdf;
// Install via NuGet: Install-Package IronPdf

var pdf = PdfDocument.FromFile("employee-form.pdf");
var field = pdf.Form.FindFormField("fullName");
field.Value = "Jane Smith";
pdf.SaveAs("completed-form.pdf");
Enter fullscreen mode Exit fullscreen mode

This code opens a PDF with a text field named "fullName", fills it with "Jane Smith", and saves the result.

Why Fill Forms Programmatically?

Manual form filling is error-prone and slow. Programmatic filling ensures:

  • Consistency: Same data source for all forms
  • Speed: Hundreds of forms filled in seconds
  • Accuracy: No typos or missed fields
  • Auditability: Log every form submission with timestamps
  • Integration: Connect forms to databases, APIs, or business logic

I built a web API that accepts employee data and returns completed onboarding PDFs. HR hits one endpoint instead of opening PDFs manually.

How Do I Find Form Fields?

Use FindFormField with the field name. Field names are set when the PDF form is created (usually in Adobe Acrobat or similar tools).

using IronPdf;

var pdf = PdfDocument.FromFile("form.pdf");
var field = pdf.Form.FindFormField("firstName");

if (field != null)
{
    field.Value = "John";
}
Enter fullscreen mode Exit fullscreen mode

If the field doesn't exist, FindFormField returns null. Always check before assigning values to avoid null reference exceptions.

How Do I List All Form Fields?

Iterate through pdf.Form.Fields to discover all field names:

using IronPdf;

var pdf = PdfDocument.FromFile("form.pdf");

foreach (var field in pdf.Form.Fields)
{
    Console.WriteLine($"Field: {field.Name}, Type: {field.Type}, Value: {field.Value}");
}
Enter fullscreen mode Exit fullscreen mode

This outputs every field name, type (text, checkbox, etc.), and current value. I use this when working with unfamiliar PDFs to understand the form structure before automating.

How Do I Fill Text Fields?

Assign the Value property:

using IronPdf;

var pdf = PdfDocument.FromFile("application.pdf");

pdf.Form.FindFormField("firstName").Value = "Sarah";
pdf.Form.FindFormField("lastName").Value = "Connor";
pdf.Form.FindFormField("email").Value = "sarah.connor@example.com";

pdf.SaveAs("filled-application.pdf");
Enter fullscreen mode Exit fullscreen mode

Text fields accept any string. For multi-line fields (text areas), use \r\n for line breaks:

pdf.Form.FindFormField("address").Value = "123 Main St\r\nApt 4B\r\nNew York, NY 10001";
Enter fullscreen mode Exit fullscreen mode

This produces three lines in the address field.

How Do I Check Checkboxes?

Set the Value property to "Yes" (case-insensitive):

using IronPdf;

var pdf = PdfDocument.FromFile("consent-form.pdf");

var agreementBox = pdf.Form.FindFormField("agreeToTerms");
agreementBox.Value = "Yes";

pdf.SaveAs("signed-consent.pdf");
Enter fullscreen mode Exit fullscreen mode

To uncheck, set Value to "Off" or null:

agreementBox.Value = "Off"; // Unchecks the box
Enter fullscreen mode Exit fullscreen mode

I used this to auto-check consent boxes in forms where employees had already agreed via our web portal.

How Do I Select Dropdown Values?

Dropdowns (comboboxes) work like text fields—set Value to one of the available options:

using IronPdf;

var pdf = PdfDocument.FromFile("enrollment.pdf");

var plan = pdf.Form.FindFormField("healthPlan");
plan.Value = "Gold Plan";

pdf.SaveAs("enrollment-gold.pdf");
Enter fullscreen mode Exit fullscreen mode

If you set an invalid value (not in the dropdown list), the field remains empty. To see available options, check the Choices property:

var plan = pdf.Form.FindFormField("healthPlan");

foreach (var choice in plan.Choices)
{
    Console.WriteLine(choice);
}
Enter fullscreen mode Exit fullscreen mode

This prints all dropdown options. I use this to validate data before assigning values.

How Do I Select Radio Buttons?

Radio buttons in the same group share one form field. Set Value to the label of the button you want selected:

using IronPdf;

var pdf = PdfDocument.FromFile("survey.pdf");

var satisfaction = pdf.Form.FindFormField("satisfactionRating");
satisfaction.Value = "Satisfied";

pdf.SaveAs("completed-survey.pdf");
Enter fullscreen mode Exit fullscreen mode

The Annotations property lists all available radio button options:

var satisfaction = pdf.Form.FindFormField("satisfactionRating");

foreach (var option in satisfaction.Annotations)
{
    Console.WriteLine(option.Value);
}
Enter fullscreen mode Exit fullscreen mode

This outputs labels like "Very Satisfied", "Satisfied", "Neutral", etc.

Can I Fill Forms from a Database?

Yes. Pull data from SQL, Entity Framework, or any data source:

using IronPdf;
using System.Data.SqlClient;

var connectionString = "Server=...;Database=...;";
var employeeId = 12345;

using (var conn = new SqlConnection(connectionString))
{
    conn.Open();
    var cmd = new SqlCommand("SELECT FirstName, LastName, Email FROM Employees WHERE Id = @id", conn);
    cmd.Parameters.AddWithValue("@id", employeeId);

    using (var reader = cmd.ExecuteReader())
    {
        if (reader.Read())
        {
            var pdf = PdfDocument.FromFile("onboarding-form.pdf");

            pdf.Form.FindFormField("firstName").Value = reader["FirstName"].ToString();
            pdf.Form.FindFormField("lastName").Value = reader["LastName"].ToString();
            pdf.Form.FindFormField("email").Value = reader["Email"].ToString();

            pdf.SaveAs($"onboarding-{employeeId}.pdf");
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

This generates a personalized PDF for each employee without manual data entry.

How Do I Fill Forms in a Loop?

Process multiple records by looping through your data:

using IronPdf;

var employees = GetEmployeesFromDatabase(); // Returns List<Employee>

foreach (var employee in employees)
{
    var pdf = PdfDocument.FromFile("template-form.pdf");

    pdf.Form.FindFormField("fullName").Value = $"{employee.FirstName} {employee.LastName}";
    pdf.Form.FindFormField("email").Value = employee.Email;
    pdf.Form.FindFormField("startDate").Value = employee.StartDate.ToString("MM/dd/yyyy");

    pdf.SaveAs($"forms/employee-{employee.Id}.pdf");
}
Enter fullscreen mode Exit fullscreen mode

This generates one PDF per employee from a single template. I process hundreds of forms overnight using this pattern.

What If Field Names Are Unknown?

Use the field discovery code to inspect the PDF first:

var pdf = PdfDocument.FromFile("unknown-form.pdf");

foreach (var field in pdf.Form.Fields)
{
    Console.WriteLine($"{field.Name}: {field.Type}");
}
Enter fullscreen mode Exit fullscreen mode

Run this once, note the field names, then hardcode them in your production code. Most forms have descriptive names like "firstName", "address", "phoneNumber".

Can I Validate Field Values?

Check field properties before assigning:

var field = pdf.Form.FindFormField("age");

if (field.Type == FormFieldTypes.Text)
{
    int age = 30;
    field.Value = age.ToString();
}
Enter fullscreen mode Exit fullscreen mode

For dropdowns, ensure the value exists in Choices:

var plan = pdf.Form.FindFormField("insurancePlan");
string desiredPlan = "Platinum";

if (plan.Choices.Contains(desiredPlan))
{
    plan.Value = desiredPlan;
}
else
{
    Console.WriteLine($"Plan '{desiredPlan}' not available");
}
Enter fullscreen mode Exit fullscreen mode

This prevents silent failures where fields remain empty due to invalid values.

How Do I Handle Missing Fields?

Always null-check before assigning:

var field = pdf.Form.FindFormField("optionalField");

if (field != null)
{
    field.Value = "Some Value";
}
else
{
    Console.WriteLine("Field 'optionalField' not found");
}
Enter fullscreen mode Exit fullscreen mode

Or use a helper method:

void SafeSetField(PdfDocument pdf, string fieldName, string value)
{
    var field = pdf.Form.FindFormField(fieldName);
    if (field != null)
    {
        field.Value = value;
    }
    else
    {
        Console.WriteLine($"Warning: Field '{fieldName}' not found");
    }
}
Enter fullscreen mode Exit fullscreen mode

This prevents crashes and logs missing fields for debugging.

Can I Clear All Form Fields?

Yes, iterate and reset values:

using IronPdf;

var pdf = PdfDocument.FromFile("filled-form.pdf");

foreach (var field in pdf.Form.Fields)
{
    field.Value = null;
}

pdf.SaveAs("blank-form.pdf");
Enter fullscreen mode Exit fullscreen mode

This resets the form to its original blank state.

How Do I Flatten Forms After Filling?

Flattening converts interactive fields to static text, making the PDF read-only:

using IronPdf;

var pdf = PdfDocument.FromFile("form.pdf");

pdf.Form.FindFormField("name").Value = "John Doe";
pdf.Form.Flatten();

pdf.SaveAs("flattened-form.pdf");
Enter fullscreen mode Exit fullscreen mode

Flattened forms can't be edited, which is useful for final submitted documents or archival copies.

What About Alternatives to IronPDF?

iTextSharp can fill forms via AcroFields.SetField(). It works but requires more boilerplate, and licensing is complex for commercial projects.

Syncfusion PDF Library has similar functionality with PdfLoadedDocument and form field manipulation. It's a good alternative if you're already using Syncfusion components.

Aspose.PDF supports form filling but is expensive for small teams. The API is comprehensive but verbose.

I chose IronPDF because the syntax is concise (FindFormField + Value assignment), licensing is straightforward, and it integrates cleanly with our existing .NET stack.

How Do I Handle Form Filling Errors?

Wrap operations in try-catch:

using IronPdf;

try
{
    var pdf = PdfDocument.FromFile("form.pdf");

    pdf.Form.FindFormField("name").Value = "Test User";
    pdf.SaveAs("output.pdf");
}
catch (Exception ex)
{
    Console.WriteLine($"Failed to fill form: {ex.Message}");
    // Log error, alert admin, etc.
}
Enter fullscreen mode Exit fullscreen mode

Common errors: corrupted PDFs, missing fields, read-only forms. I log these to Application Insights and send alerts if the error rate exceeds 5%.

Can I Fill Forms in Memory Without Saving?

Yes, use streams:

using IronPdf;
using System.IO;

var pdfBytes = File.ReadAllBytes("form.pdf");
using (var stream = new MemoryStream(pdfBytes))
{
    var pdf = PdfDocument.FromStream(stream);

    pdf.Form.FindFormField("name").Value = "John";

    var outputStream = pdf.Stream;
    // Send outputStream to web response, save to blob storage, etc.
}
Enter fullscreen mode Exit fullscreen mode

This is useful in web APIs where you don't want to write files to disk.

How Do I Send Filled Forms via Email?

Generate the PDF in memory and attach it:

using IronPdf;
using System.Net.Mail;
using System.IO;

var pdf = PdfDocument.FromFile("form.pdf");
pdf.Form.FindFormField("recipientName").Value = "Jane Doe";

var pdfStream = pdf.Stream;
var attachment = new Attachment(pdfStream, "completed-form.pdf", "application/pdf");

var mail = new MailMessage();
mail.To.Add("recipient@example.com");
mail.Subject = "Your Completed Form";
mail.Body = "Please find your completed form attached.";
mail.Attachments.Add(attachment);

var smtp = new SmtpClient("smtp.example.com");
smtp.Send(mail);
Enter fullscreen mode Exit fullscreen mode

We use this to email completed onboarding forms to new employees automatically.


Written by Jacob Mellor, CTO at Iron Software. Jacob created IronPDF and leads a team of 50+ engineers building .NET document processing libraries.

Top comments (0)