How to Get Form Field from PDF in C#, VB.NET

Form field is used for users to interact with PDF document, for instance, users can fill the textbox forms with data or select an item from a pre-defined drop down list. But before we assign value to a form field, we need to specify the field. This article presents how to get all form fields or a specific field using Spire.PDF in C# and VB.NET.

Code Snippet:

Step 1: Initialize an instance of PdfDocument class. Load a sample PDF file to it.

PdfDocument doc = new PdfDocument();
doc.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.pdf");

Step 2: Spire.PDF provides a class of FieldsWidget which represents field collection of loaded forms. Traverse the FieldsWidget.List to get each item of form fields and print the field name to console.

PdfFormWidget formWidget = doc.Form as PdfFormWidget;
for (int i = 0; i < formWidget.FieldsWidget.List.Count; i++)
{
    PdfField field = formWidget.FieldsWidget.List[i] as PdfField;
    string fieldName = field.Name;
    Console.WriteLine(fieldName);                     
}

Step 3: Besides using FieldsWidget.List to get fields from PDF, Spire.PDF also supports to get the specified field(s) by export value. Following code snippet prints the names of fields whose export value is "Yes".

List list = formWidget.FieldsWidget.GetFieldsByExportValue("Yes");
for (int i = 0; i < list.Count; i++)
{
    string fieldName = list[i].Name;
    Console.WriteLine(fieldName);
}

Output:

How to Get Form Field from PDF in C#, VB.NET

Full Code:

[C#]
PdfDocument doc = new PdfDocument();
doc.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.pdf");

PdfFormWidget formWidget = doc.Form as PdfFormWidget;
for (int i = 0; i < formWidget.FieldsWidget.List.Count; i++)
{
    PdfField field = formWidget.FieldsWidget.List[i] as PdfField;
    string fieldName = field.Name;
    Console.WriteLine(fieldName);                     
}
Console.WriteLine("--------------------------------------");

List list = formWidget.FieldsWidget.GetFieldsByExportValue("Yes");
for (int i = 0; i < list.Count; i++)
{
    string fieldName = list[i].Name;
    Console.WriteLine(fieldName);
}
Console.Read();
[VB.NET]
Dim doc As New PdfDocument()
doc.LoadFromFile("C:\Users\Administrator\Desktop\sample.pdf")

Dim formWidget As PdfFormWidget = TryCast(doc.Form, PdfFormWidget)
For i As Integer = 0 To formWidget.FieldsWidget.List.Count - 1
	Dim field As PdfField = TryCast(formWidget.FieldsWidget.List(i), PdfField)

    Dim fieldName As String = field.Name

    Console.WriteLine(fieldName)
Next
Console.WriteLine("--------------------------------------")

Dim list As List(Of PdfField) = formWidget.FieldsWidget.GetFieldsByExportValue("Yes")
For i As Integer = 0 To list.Count - 1
	Dim fieldName As String = list(i).Name

    Console.WriteLine(fieldName)
Next
Console.Read()