Required fields force the user to fill in the selected form field. If the user attempts to submit the form while a required field is blank, an error message appears and the empty required form field is highlighted.
Using Spire.PDF, we're able to enforce a form field as "Required" or determine which fields are required in an existing PDF document. This article mainly introduce how to detect the required form fields in C# and VB.NET.
Code Snippet:
Step 1: Initialize an instance of PdfDocument class and load a sample PDF file that contains some form fields.
PdfDocument doc = new PdfDocument(); doc.LoadFromFile(@"C: \Users\Administrator\Desktop\PdfFormExample.pdf");
Step 2: Get all form widgets from the PDF document.
PdfFormWidget formWidget = doc.Form as PdfFormWidget;
Step 3: Traverse the form widgets to find the form field that is required and print all results on console.
for (int i = 0; i < formWidget.FieldsWidget.List.Count; i++) { PdfField field = formWidget.FieldsWidget.List[i] as PdfField; string fieldName = field.Name; bool isRequired = field.Required; if (isRequired) { Console.WriteLine(fieldName + " is required."); } }
Output:
Full Code:
[C#]
using Spire.Pdf; using Spire.Pdf.Fields; using Spire.Pdf.Widget; using System; namespace Detect { class Program { static void Main(string []args) { PdfDocument doc = new PdfDocument(); doc.LoadFromFile(@"C: \Users\Administrator\Desktop\PdfFormExample.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; bool isRequired = field.Required; if (isRequired) { Console.WriteLine(fieldName + " is required."); } } Console.ReadKey(); } } }
[VB.NET]
Imports Spire.Pdf Imports Spire.Pdf.Fields Imports Spire.Pdf.Widget Namespace Detect Class Program Private Shared Sub Main(args As String()) Dim doc As New PdfDocument() doc.LoadFromFile("C: \Users\Administrator\Desktop\PdfFormExample.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 Dim isRequired As Boolean = field.Required If isRequired Then Console.WriteLine(fieldName & Convert.ToString(" is required.")) End If Next Console.ReadKey() End Sub End Class End Namespace