ImageGear v26.5 - Updated
Developer Guide / How to Work with ... / PDF / How to... / Work with PDF Forms / Traverse Form Fields
In This Topic
    Traverse Form Fields
    In This Topic

    PDF forms contain an array of fields that are represented as individual controls or groups of controls on the pages of a PDF. You can iterate through this array and manipulate these controls to change their values.

    All AcroForms-based access to the PDF fields is provided by the Fields property of an ImGearPDFDocument.Form. If a loaded PDF document has no form, the Form property will be null. Use CreateForm to create an empty form.

    If a loaded PDF document has broken form data, the Form property will be null and a warning occurs with the message, "Error reading Acroform. Acroform was not loaded."

    You can access fields though iteration or index-based access. Iteration is accomplished through an IEnumerable object; the indexed access provides two interfaces: by full name or by numerical field index. Once a Field object is obtained, see Read and Write Form Field Values to read values.

    Iterating over Form Fields

    Iteration over the Fields property can be done using a foreach loop, a for loop, or any method consuming an IEnumerable object. Fields returns the number of fields in the PDF form.

    The iteration order of fields is the layout of the internal AcroForm element of the PDF, which is not necessarily per-page or from top to bottom. No order should be assumed.

    C#

    void IterateFormFields(ImGearPDFDocument pdf)
    {
        if (pdf.Form == null)
        {
            pdf.CreateForm();
        }
        foreach (Field field in pdf.Form.Fields)
        {
            // Operate on the field here...
        }
        for (int i = 0; i != pdf.Form.Fields.Count; ++i)
        {
            // Operate on the field here...
        }
    }
    

    Index-Based Traversal

    Index-based traversal allows random access to fields. When indexing by name, the name is the full name of the field. A full name is a number of partial names separated by periods: see the FullName property for details. The numerical index order is the same as the iteration order, as mentioned above.

    C#

    void ProcessFields(ImGearPDFDocument pdf)
    {
        var name = pdf.Form.Fields[0];
        var address = pdf.Form.Fields["address.state.county"];
        // Operate on the fields here...
    }