C# .NET PDF Form Library

The guide explains how to fill form fields programmatically in a PDF document. This feature enables you to, for example, fill in many forms in one go with values from a database.

To fill form fields programmatically in a PDF document, follow these steps:

  1. Create a GdPicturePDF object.

  2. Determine the number of form fields in the document with the GetFormFieldsCount method.

  3. Loop through the form fields.

  4. For each form field, determine the title with the GetFormFieldId and GetFormFieldTitle methods.

  5. If the title matches your conditions, such as family or given name, set a value for the form field with the SetFormFieldValue method.

  6. Save the output in a new PDF file with the SaveToFile method.

The code below opens a fillable PDF document, fills in two form fields, and saves the output in a new PDF file:

using GdPicturePDF gdpicturePDF = new GdPicturePDF();
// Load the source document.
gdpicturePDF.LoadFromFile(@"C:\temp\source.pdf");
// Determine the number of form fields.
int formFieldCount = gdpicturePDF.GetFormFieldsCount();
// Loop through the form fields.
for (int formFieldIndex = 0; formFieldIndex <= formFieldCount - 1; formFieldIndex++)
{
    // Determine the title of the form field.
    int formFieldId = gdpicturePDF.GetFormFieldId(formFieldIndex);
    string formFieldTitle = gdpicturePDF.GetFormFieldTitle(formFieldId);
    // Set a value for the form field.
    if (formFieldTitle== "Family Name")
    {
        gdpicturePDF.SetFormFieldValue(formFieldId, "Doe");
    }
    else if (formFieldTitle == "Given Name")
    {
        gdpicturePDF.SetFormFieldValue(formFieldId, "Jane");
    }
}
// Save the output in a new PDF file.
gdpicturePDF.SaveToFile(@"C:\temp\output.pdf");
Using gdpicturePDF As GdPicturePDF = New GdPicturePDF()
    ' Load the source document.
    gdpicturePDF.LoadFromFile("C:\temp\source.pdf")
    ' Determine the number of form fields.
    Dim formFieldCount As Integer = gdpicturePDF.GetFormFieldsCount()
    ' Loop through the form fields.
    For formFieldIndex = 0 To formFieldCount - 1
        ' Determine the title of the form field.
        Dim formFieldId As Integer = gdpicturePDF.GetFormFieldId(formFieldIndex)
        Dim formFieldTitle As String = gdpicturePDF.GetFormFieldTitle(formFieldId)
        ' Set a value for the form field.
        If Equals(formFieldTitle, "Family Name") Then
            gdpicturePDF.SetFormFieldValue(formFieldId, "Doe")
        ElseIf Equals(formFieldTitle, "Given Name") Then
            gdpicturePDF.SetFormFieldValue(formFieldId, "Jane")
        End If
    Next
    ' Save the output in a new PDF file.
    gdpicturePDF.SaveToFile("C:\temp\output.pdf")
End Using
Used Methods and Properties

Related Topics