C#: Import and Export PDF Form Data
Importing and exporting PDF form data allows users to seamlessly exchange form information with external files in formats such as FDF (Forms Data Format), XFDF (XML Forms Data Format), or XML. The import function enables quick population of PDF forms using data from external sources, while the export function extracts data from PDF forms and saves it to external files. This capability simplifies data management, making it especially valuable for processing large volumes of form data or integrating with other systems. In this article, we will demonstrate how to import PDF form data from FDF, XFDF, or XML files, or export PDF form data to FDF, XFDF, or XML files in C# using Spire.PDF for .NET.
- Import PDF Form Data from FDF, XFDF or XML Files in C#
- Export PDF Form Data to FDF, XFDF or XML Files in C#
Install Spire.PDF for .NET
To begin with, you need to add the DLL files included in the Spire.PDF for.NET package as references in your .NET project. The DLLs files can be either downloaded from this link or installed via NuGet.
PM> Install-Package Spire.PDF
Import PDF Form Data from FDF, XFDF or XML Files in C#
Spire.PDF for .NET offers the PdfFormWidget.ImportData() method for importing PDF form data from FDF, XFDF, or XML files. The detailed steps are as follows.
- Create an object of the PdfDocument class.
- Load a PDF document using PdfDocument.LoadFromFile() method.
- Get the form of the PDF document using PdfDocument.Form property.
- Import form data from an FDF, XFDF or XML file using PdfFormWidget.ImportData() method.
- Save the resulting document using PdfDocument.SaveToFile() method.
- C#
using Spire.Pdf; using Spire.Pdf.Widget; namespace ImportPdfFormData { internal class Program { static void Main(string[] args) { //Create an object of the PdfDocument class PdfDocument document = new PdfDocument(); //Load a PDF document document.LoadFromFile("Forms.pdf"); //Get the form of the PDF document PdfFormWidget loadedForm = document.Form as PdfFormWidget; //Import PDF form data from an XML file loadedForm.ImportData("Data.xml", DataFormat.Xml); //Import PDF form data from an FDF file //loadedForm.ImportData("Data.fdf", DataFormat.Fdf); //Import PDF form data from an XFDF file //loadedForm.ImportData("Data.xfdf", DataFormat.XFdf); //Save the resulting document document.SaveToFile("Output.pdf"); //Close the PdfDocument object document.Close(); } } }
Export PDF Form Data to FDF, XFDF or XML Files in C#
Spire.PDF for .NET also enables you to export PDF form data to FDF, XFDF, or XML files by using the PdfFormWidget.ExportData() method. The detailed steps are as follows.
- Create an object of the PdfDocument class.
- Load a PDF document using PdfDocument.LoadFromFile() method.
- Get the form of the PDF document using PdfDocument.Form property.
- Export form data to an FDF, XFDF or XML file using PdfFormWidget.ExportData() method.
- C#
using Spire.Pdf; using Spire.Pdf.Fields; using Spire.Pdf.Widget; namespace ExportPdfFormData { internal class Program { static void Main(string[] args) { //Create an object of the PdfDocument class PdfDocument document = new PdfDocument(); //Load a PDF document document.LoadFromFile("Forms.pdf"); //Get the form of the PDF document PdfFormWidget loadedForm = document.Form as PdfFormWidget; //Export PDF form data to an XML file loadedForm.ExportData("Data.xml", DataFormat.Xml, "Form"); //Export PDF form data to an FDF file //loadedForm.ExportData("Data.fdf", DataFormat.Fdf, "Form"); //Export PDF form data to an XFDF file //loadedForm.ExportData("Data.xfdf", DataFormat.XFdf, "Form"); //Close the PdfDocument object document.Close(); } } }
Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
Remove/Delete Form Fields from PDF in C#
This article demonstrates how to remove a particular form field and all of the form fields from an existing PDF document using Spire.PDF.
The below sample document contains some text and five different kinds of form fields:
Remove a particular form field
We can remove a particular form field by calling the PdfFieldCollection.Remove method. To remove the form field by index, call the PdfFieldCollection.RemoveAt method and pass the corresponding index of the form field as the argument.
using Spire.Pdf; using Spire.Pdf.Fields; using Spire.Pdf.Widget; namespace RemoveSpecifiedFormfield { class Program { static void Main(string[] args) { //Create PdfDocument instance PdfDocument pdf = new PdfDocument(); //Load PDF file pdf.LoadFromFile(@"Input.pdf"); //Get form fields PdfFormWidget formWidget = pdf.Form as PdfFormWidget; //Get and remove the first form field PdfField textbox = formWidget.FieldsWidget.List[0] as PdfTextBoxFieldWidget; formWidget.FieldsWidget.Remove(textbox); //Get and remove the first form field using its name //PdfField field = formWidget.FieldsWidget["Text1"]; //formWidget.FieldsWidget.Remove(field); //Remove the form field at index 0 //formWidget.FieldsWidget.RemoveAt(0); pdf.SaveToFile("DeleteParticularField.pdf"); } } }
Remove all of the form fields
To remove all of the form fields, first we need to traverse the form fields and then remove them one by one.
using Spire.Pdf; using Spire.Pdf.Fields; using Spire.Pdf.Widget; namespace RemoveSpecifiedFormfield { class Program { static void Main(string[] args) { //Create PdfDocument instance PdfDocument pdf = new PdfDocument(); //Load PDF file pdf.LoadFromFile(@"Input.pdf"); //Get form fields PdfFormWidget formWidget = pdf.Form as PdfFormWidget; //Remove all of the form fields for (int i = formWidget.FieldsWidget.List.Count - 1; i >= 0; i--) { PdfField field = formWidget.FieldsWidget.List[i] as PdfField; formWidget.FieldsWidget.Remove(field); } pdf.SaveToFile("DeleteAllFields.pdf"); } } }
Assign an Icon to a PDF Button Field and Set Icon Layout in C#
In PDF, buttons can be assigned icon appearances and each button can have as many as three appearances: Normal, Rollover, and Click. With Spire.PDF, not only can we assign icons to buttons, but also we can change the icons of buttons. In this article, we’re going to show you how to assign an icon to a button and set icon layout using Spire.PDF and C#. As for changing icons, please refer How to change the image on button field in C#.
Code Snippets:
Step 1: Create a PDF document and add a page to it.
PdfDocument doc = new PdfDocument(); PdfPageBase page = doc.Pages.Add();
Step 2: Create a button field.
PdfButtonField btn = new PdfButtonField(page, "button1"); btn.Bounds = new RectangleF(0, 50, 120, 100);
Step 3: Set button layout.
btn.HighlightMode = PdfHighlightMode.Push; btn.LayoutMode = PdfButtonLayoutMode.CaptionOverlayIcon; //Set text and icon for Normal appearance btn.Text = "Normal Text"; btn.Icon = PdfImage.FromFile("Image.png"); //Set text and icon for Click appearance (Can only be set when highlight mode is Push) btn.AlternateText = "Alternate Text"; btn.AlternateIcon = PdfImage.FromFile("Sunflower.jpg"); //Set text and icon for Rollover appearance (Can only be set when highlight mode is Push) btn.RolloverText = "Rollover Text"; btn.RolloverIcon = PdfImage.FromFile("PinkRoses.jpg");
Step 4: Set icon layout.
btn.IconLayout.Spaces = new float[] { 0.5f, 0.5f }; btn.IconLayout.ScaleMode = PdfButtonIconScaleMode.Proportional; btn.IconLayout.ScaleReason = PdfButtonIconScaleReason.Always; btn.IconLayout.IsFitBounds = false;
Step 5: Add the button to the document.
doc.Form.Fields.Add(btn);
Step 6: Save the document.
doc.SaveToFile("AddIcon.pdf");
The resultant document looks as follows:
Full code:
using System.Drawing; using Spire.Pdf; using Spire.Pdf.Fields; using Spire.Pdf.Graphics; namespace Add_Icon_to_PDF_Button_Field { class Program { static void Main(string[] args) { //Create a PDF document PdfDocument doc = new PdfDocument(); PdfPageBase page = doc.Pages.Add(); //Create a Button PdfButtonField btn = new PdfButtonField(page, "button1"); btn.Bounds = new RectangleF(0, 50, 120, 100); btn.HighlightMode = PdfHighlightMode.Push; btn.LayoutMode = PdfButtonLayoutMode.CaptionOverlayIcon; //Set text and icon for Normal appearance btn.Text = "Normal Text"; btn.Icon = PdfImage.FromFile("Image.png"); //Set text and icon for Click appearance (Can only be set when highlight mode is Push) btn.AlternateText = "Alternate Text"; btn.AlternateIcon = PdfImage.FromFile("Sunflower.jpg"); //Set text and icon for Rollover appearance (Can only be set when highlight mode is Push) btn.RolloverText = "Rollover Text"; btn.RolloverIcon = PdfImage.FromFile("PinkRoses.jpg"); //Set icon layout btn.IconLayout.Spaces = new float[] { 0.5f, 0.5f }; btn.IconLayout.ScaleMode = PdfButtonIconScaleMode.Proportional; btn.IconLayout.ScaleReason = PdfButtonIconScaleReason.Always; btn.IconLayout.IsFitBounds = false; //Add the button to the document doc.Form.Fields.Add(btn); //Save the document doc.SaveToFile("AddIcon.pdf"); } } }
Set "Commit selected value immediately" property for ComboBox field and ListBox field
When we operate the ComboBox field and ListBox field on PDF files, we can set the options for Dropdown Properties. This article will focus on how you how to set "Commit selected value immediately" property for ComboBox field and ListBox field. We will divide into two parts for how to set the property of "Commit selected value immediately", one is for the existing field on PDF and the other is for the new field added to the PDF file.
The following code is for how to set "Commit selected value immediately" property for the existing ListBox field on PDF:
//create a PDF document and load the document from file PdfDocument pdf = new PdfDocument(); pdf.LoadFromFile("FormField.pdf"); //get the existing form PdfFormWidget fw = pdf.Form as PdfFormWidget; //get the ListBox field and set the field of CommitOnSelChange property as true if (fw != null) { for (int i = 0; i < fw.FieldsWidget.Count; i++) { if (fw.FieldsWidget[i] != null) { if (fw.FieldsWidget[i] is PdfListBoxWidgetFieldWidget) { (fw.FieldsWidget[i] as PdfListBoxWidgetFieldWidget).CommitOnSelChange = true; } } } } pdf.SaveToFile("Result.pdf");
The following code is for how to set the property of "Commit selected value immediately" for ComboBox field when we add a new ComboBox field on PDF:
using (PdfDocument pdf = new PdfDocument()) { PdfPageBase page = pdf.Pages.Add(); //add a new ComboBox Field and add data to it PdfComboBoxField combo = new PdfComboBoxField(page, "ComboBox"); combo.Bounds = new RectangleF(20, 20,60, 20); PdfListFieldItem item1 = new PdfListFieldItem("First", "1"); PdfListFieldItem item2 = new PdfListFieldItem("Second", "2"); combo.Items.Add(item1); combo.Items.Add(item2); //set the field of CommitOnSelChange property as true combo.CommitOnSelChange = true; pdf.Form.Fields.Add(combo); pdf.SaveToFile("Result2.Pdf"); }
C#/VB.NET: Flatten Form Fields in PDF
Flattening form fields is an efficient way to prevent others from modifying or deleting the form field contents in PDF. After flattening, the editing or filling capability of the form fields will be removed and their contents will appear as regular text. In this article, you will learn how to flatten form fields in a PDF document in C# and VB.NET using Spire.PDF for .NET.
Install Spire.PDF for .NET
To begin with, you need to add the DLL files included in the Spire.PDF for.NET package as references in your .NET project. The DLLs files can be either downloaded from this link or installed via NuGet.
PM> Install-Package Spire.PDF
Flatten a Specific Form Field in PDF in C# and VB.NET
The following are the steps to flatten a specific form field in a PDF document using Spire.PDF for .NET:
- Initialize an instance of PdfDocument class.
- Load a PDF document using PdfDocument.LoadFromFile() method.
- Get the form widget collection from the document.
- Get a specific form field from the widget collection by its name or index through PdfFormWidget.FieldsWidget["fieldName"] property or PdfFormWidget.FieldsWidget.List[fieldIndex] property.
- Flatten the form field through PdfField.Flatten property.
- Save the result document using PdfDocument.SaveToFile() method.
- C#
- VB.NET
using Spire.Pdf; using Spire.Pdf.Fields; using Spire.Pdf.Widget; namespace FlattenSpecificFormField { class Program { static void Main(string[] args) { //Create a PdfDocument instance PdfDocument pdf = new PdfDocument(); //Load a PDF document pdf.LoadFromFile("Form.pdf"); //Get the form widget collection PdfFormWidget formWidget = (PdfFormWidget)pdf.Form; //Get a specific form field by its name PdfField form = formWidget.FieldsWidget["Address"]; //Get a specific form field by its index //PdfField form = formWidget.FieldsWidget.List[2] as PdfField; //Flatten the form form.Flatten = true; //Save the result document pdf.SaveToFile("FlattenSpecific.pdf"); } } }
Flatten All Form Fields in PDF in C# and VB.NET
The following are the steps to flatten all the form fields in a PDF document using Spire.PDF for .NET:
- Initialize an instance of PdfDocument class.
- Load a PDF document using PdfDocument.LoadFromFile() method.
- Flatten all the form fields in the document through PdfDocument.Form.IsFlatten property.
- Save the result document using PdfDocument.SaveToFile() method.
- C#
- VB.NET
using Spire.Pdf; namespace FlattenAllFormFields { class Program { static void Main(string[] args) { //Create a PdfDocument instance PdfDocument pdf = new PdfDocument(); //Load a PDF document pdf.LoadFromFile("Form.pdf"); //Flatten all the forms in the document pdf.Form.IsFlatten = true; //Save the result document pdf.SaveToFile("FlattenAll.pdf"); } } }
Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
Fill XFA Form Fields in C#/VB.NET
XFA forms are XML-based forms created by Adobe's LiveCycle Designer tool, which offer enhanced features over the old AcroForms, like changeable text fields and support for running JavaScript. Spire.PDF supports to access the XFA forms in an existing PDF file and fill the fields with data.
Step 1: Initialize an instance of PdfDocument class and load a sample PDF file containing dynamic XFA forms.
PdfDocument doc = new PdfDocument(); doc.LoadFromFile("DynamicXFA.pdf");
Step 2: Get all form widgets from the document.
PdfFormWidget formWidget = doc.Form as PdfFormWidget;
Step 3: Get a list of XFA Fields.
List<XfaField> xfafields = formWidget.XFAForm.XfaFields;
Step 4: Traverse each XfaField in the list and judge if it is an XfaTextField, if yes, convert the type of XfaField as an XfaTextField and then assign value to the field based on the field name.
foreach (XfaField xfaField in xfaFields) { if (xfaField is XfaTextField) { XfaTextField xf = xfaField as XfaTextField; switch (xfaField.Name) { case "EmployeeName": xf.Value = "Gary"; break; case "Address": xf.Value = "Chengdu, China"; break; case "StateProv": xf.Value = "Sichuan Province"; break; case "ZipCode": xf.Value = "610093"; break; case "SSNumber": xf.Value = "000-00-0000"; break; case "HomePhone": xf.Value = "86-028-81705109"; break; case "CellPhone": xf.Value = "123456789"; break; case "Comments": xf.Value = "This demo shows how to fill XFA forms using Spire.PDF"; break; default: break; } } }
Step 5: Save the file.
doc.SaveToFile("FillXfaField.pdf",FileFormat.PDF);
Output:
Full Code:
using Spire.Pdf; using Spire.Pdf.Widget; using System.Collections.Generic; namespace FillXFAFormFields { class Program { private static IEnumerable xfaFields; static void Main(string []args) { PdfDocument doc = new PdfDocument(); doc.LoadFromFile("DynamicXFA.pdf"); PdfFormWidget formWidget = doc.Form as PdfFormWidget; List xfafields = formWidget.XFAForm.XfaFields; foreach (XfaField xfaField in xfaFields) { if (xfaField is XfaTextField) { XfaTextField xf = xfaField as XfaTextField; switch (xfaField.Name) { case "EmployeeName": xf.Value = "Gary"; break; case "Address": xf.Value = "Chengdu, China"; break; case "StateProv": xf.Value = "Sichuan Province"; break; case "ZipCode": xf.Value = "610093"; break; case "SSNumber": xf.Value = "000-00-0000"; break; case "HomePhone": xf.Value = "86-028-81705109"; break; case "CellPhone": xf.Value = "123456789"; break; case "Comments": xf.Value = "This demo shows how to fill XFA forms using Spire.PDF"; break; default: break; } } } doc.SaveToFile("FillXfaField.pdf", FileFormat.PDF); } } }
Imports Spire.Pdf Imports Spire.Pdf.Widget Imports System.Collections.Generic Namespace FillXFAFormFields Class Program Private Shared xfaFields As IEnumerable(Of XfaField) Private Shared Sub Main(args As String()) Dim doc As New PdfDocument() doc.LoadFromFile("DynamicXFA.pdf") Dim formWidget As PdfFormWidget = TryCast(doc.Form, PdfFormWidget) Dim xfafields__1 As List(Of XfaField) = formWidget.XFAForm.XfaFields For Each xfaField As XfaField In xfaFields If TypeOf xfaField Is XfaTextField Then Dim xf As XfaTextField = TryCast(xfaField, XfaTextField) Select Case xfaField.Name Case "EmployeeName" xf.Value = "Gary" Exit Select Case "Address" xf.Value = "Chengdu, China" Exit Select Case "StateProv" xf.Value = "Sichuan Province" Exit Select Case "ZipCode" xf.Value = "610093" Exit Select Case "SSNumber" xf.Value = "000-00-0000" Exit Select Case "HomePhone" xf.Value = "86-028-81705109" Exit Select Case "CellPhone" xf.Value = "123456789" Exit Select Case "Comments" xf.Value = "This demo shows how to fill XFA forms using Spire.PDF" Exit Select Case Else Exit Select End Select End If Next doc.SaveToFile("FillXfaField.pdf", FileFormat.PDF) End Sub End Class End Namespace
Detect the Required Form Field in PDF in C#/VB.NET
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:
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(); } } }
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
C#/VB.NET: Extract Form Field Values from PDF
Form fields are often used in documents like surveys, registration forms, or feedback forms to collect data from users. Extracting form field values allows you to gather and consolidate the submitted data for further analysis or processing. In this article, we will demonstrate how to extract form field values from PDF documents in C# and VB.NET using Spire.PDF for .NET.
Install Spire.PDF for .NET
To begin with, you need to add the DLL files included in the Spire.PDF for.NET package as references in your .NET project. The DLLs files can be either downloaded from this link or installed via NuGet.
PM> Install-Package Spire.PDF
Extract Form Field Values from PDF in C# and VB.NET
In a PDF document, you may encounter various types of form fields, such as textboxes, checkboxes, radio buttons, list boxes, and combo boxes (drop-down lists). Before extracting form field values, it is crucial to identify the specific type of each form field. Once identified, you can utilize corresponding properties tailored for each form field type to accurately extract their values. The detailed steps are as follows:
- Initialize an instance of the PdfDocument instance.
- Load a PDF document using PdfDocument.LoadFromFile() method.
- Initialize an instance of the StringBuilder class for storing the extract form field values.
- Get the form from the document using PdfDocument.Form property.
- Iterate through all form fields in the form.
- Determine the types of the form fields, then get the names and values of the form fields using the corresponding properties and append them to the StringBuilder instance.
- Write the content of the StringBuilder instance into a text file.
- C#
- VB.NET
using Spire.Pdf; using Spire.Pdf.Fields; using Spire.Pdf.Widget; using System.IO; using System.Text; namespace ExtractFormFieldValues { internal class Program { static void Main(string[] args) { //Initialize an instance of the PdfDocument instance PdfDocument doc = new PdfDocument(); //Load a PDF document doc.LoadFromFile(@"Forms.pdf"); //Initialize an instance of the StringBuilder class StringBuilder sb = new StringBuilder(); //Get the form from the document PdfFormWidget formWidget = doc.Form as PdfFormWidget; //Iterate through all fields in the form for (int i = 0; i < formWidget.FieldsWidget.List.Count; i++) { PdfField field = formWidget.FieldsWidget.List[i] as PdfField; //Get the name and value of textbox field if (field is PdfTextBoxFieldWidget) { PdfTextBoxFieldWidget textBoxField = field as PdfTextBoxFieldWidget; string name = textBoxField.Name; string value = textBoxField.Text; sb.Append("Textbox Name: " + name + "\r\n"); sb.Append("Textbox Value: " + value + "\r\n"); } //Get the name, items and selected item of list box field if (field is PdfListBoxWidgetFieldWidget) { PdfListBoxWidgetFieldWidget listBoxField = field as PdfListBoxWidgetFieldWidget; string name = listBoxField.Name; sb.Append("Listbox Name: " + name + "\r\n"); sb.Append("Listbox Items: \r\n"); PdfListWidgetItemCollection items = listBoxField.Values; foreach (PdfListWidgetItem item in items) { sb.Append(item.Value + "\r\n"); } string selectedValue = listBoxField.SelectedValue; sb.Append("Listbox Selected Value: " + selectedValue + "\r\n"); } //Get the name, items and selected item of combo box field if (field is PdfComboBoxWidgetFieldWidget) { PdfComboBoxWidgetFieldWidget comBoxField = field as PdfComboBoxWidgetFieldWidget; string name = comBoxField.Name; sb.Append("Combobox Name: " + name + "\r\n"); sb.Append("Combobox Items: \r\n"); PdfListWidgetItemCollection items = comBoxField.Values; foreach (PdfListWidgetItem item in items) { sb.Append(item.Value + "\r\n"); } string selectedValue = comBoxField.SelectedValue; sb.Append("Combobox Selected Value: " + selectedValue + "\r\n"); } //Get the name and selected item of radio button field if (field is PdfRadioButtonListFieldWidget) { PdfRadioButtonListFieldWidget radioBtnField = field as PdfRadioButtonListFieldWidget; string name = radioBtnField.Name; sb.Append("Radio Button Name: " + name + "\r\n"); string selectedValue = radioBtnField.SelectedValue; sb.Append("Radio Button Selected Value: " + selectedValue + "\r\n"); } //Get the name and status of checkbox field if (field is PdfCheckBoxWidgetFieldWidget) { PdfCheckBoxWidgetFieldWidget checkBoxField = field as PdfCheckBoxWidgetFieldWidget; string name = checkBoxField.Name; sb.Append("Checkbox Name: " + name + "\r\n"); bool status = checkBoxField.Checked; if (status) { sb.Append("Checkbox Status: Checked \r\n"); } else { sb.Append("Checkbox Status: Unchecked \r\n"); } } sb.Append("\n"); } //Write the content of the StringBuilder into a text file File.WriteAllText("GetAllValues.txt", sb.ToString()); doc.Dispose(); } } }
Apply for a Temporary License
If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.
Format Textbox Field using JavaScript in C#/VB.NET
A text box can be formatted to display number, currency, date, time, zip code, phone number, social security number, etc. Adobe Acrobat provides various built-in JavaScripts, such as AFNumber_Keystroke(2, 0, 0, 0, "$", true) and AFNumber_Format(2, 0, 0, 0, "$", true), to format and validate the input of text field. The script with Format suffix is used to format the input, the script with Keystroke suffix is used to validate the input.
However, Spire.PDF has offered corresponding methods to perform formatting and validation on text field. Here is the list of frequently used formats and corresponding methods in Spire.PDF.
Description | Example | JavaScript | Method |
Date | 01/31/2008 | AFDate_FormatEx("mm/dd/yyyy"); AFDate_KeystrokeEx("mm/dd/yyyy"); |
GetDateFormatString("mm/dd/yyyy"); GetDateKeystrokeString("mm/dd/yyyy"); |
Date | 1/31/2008 | AFDate_FormatEx("m/d/yyyy"); AFDate_KeystrokeEx("m/d/yyyy"); |
GetDateFormatString("m/d/yyyy"); GetDateKeystrokeString("m/d/yyyy"); |
Zip code | 12345 | AFSpecial_Format(0); AFSpecial_Keystroke(0); |
GetSpecialFormatString(0); GetSpecialKeystrokeString(0); |
Zip+4 | 12345-1234 | AFSpecial_Format(1); AFSpecial_Keystroke(1); |
GetSpecialFormatString(1); GetSpecialKeystrokeString(1); |
Phone number | (123) 456-7890 | AFSpecial_Format(2); AFSpecial_Keystroke(2); |
GetSpecialFormatString(2); GetSpecialKeystrokeString(2); |
Money (minus sign if negative) | $12,345.00 -$12,345.00 |
AFNumber_Format(2, 0, 0, 0, "$", true); AFNumber_Keystroke(2, 0, 0, 0, "$", true); |
GetNumberFormatString(2, 0, 0, 0, "$", true); GetNumberKeystrokeString(2, 0, 0, 0, "$", true); |
Validate | 1.5≤input value≤5.5 | AFRange_Validate(true,1.5,true,5.5) | GetRangeValidateString(true, 1.5, true, 5.5); |
This tutorial demonstrates how to create a text box and display its contents in currency format in C# and VB.NET.
Code Snippets:
Step 1: Create an object of PdfDocument and add a page to it.
PdfDocument pdf = new PdfDocument(); PdfPageBase page = pdf.Pages.Add();
Step 2: Initialize an instance of PdfTextBoxField class and set its position, border width and border style.
PdfTextBoxField textbox = new PdfTextBoxField(page, "Number-TextBox"); textbox.Bounds = new RectangleF(10, 10, 100, 20); textbox.BorderWidth = 0.75f; textbox.BorderStyle = PdfBorderStyle.Solid;
Step 3: Set a JavaScript action to be performed when uses type a keystroke into a text field. This action can check the keystroke for validity and reject or modify it.
string js = PdfJavaScript.GetNumberKeystrokeString(2, 0, 0, 0, "$", true); PdfJavaScriptAction jsAction = new PdfJavaScriptAction(js); textbox.Actions.KeyPressed = jsAction;
Step 4: Set a JavaScript action to format the value of text field before showing it.
js = PdfJavaScript.GetNumberFormatString(2, 0, 0, 0, "$", true); jsAction = new PdfJavaScriptAction(js); textbox.Actions.Format = jsAction;
Step 5: Add the text box to PDF field and save the file.
pdf.Form.Fields.Add(textbox); pdf.SaveToFile("FormatField.pdf",FileFormat.PDF);
Output:
Full Code:
using Spire.Pdf; using Spire.Pdf.Actions; using Spire.Pdf.Fields; using System.Drawing; namespace FormatTextboxField { class Program { static void Main(string []args) { PdfDocument pdf = new PdfDocument(); PdfPageBase page = pdf.Pages.Add(); PdfTextBoxField textbox = new PdfTextBoxField(page, "Number-TextBox"); textbox.Bounds = new RectangleF(10, 10, 100, 20); textbox.BorderWidth = 0.75f; textbox.BorderStyle = PdfBorderStyle.Solid; string js = PdfJavaScript.GetNumberKeystrokeString(2, 0, 0, 0, "$", true); PdfJavaScriptAction jsAction = new PdfJavaScriptAction(js); textbox.Actions.KeyPressed = jsAction; js = PdfJavaScript.GetNumberFormatString(2, 0, 0, 0, "$", true); jsAction = new PdfJavaScriptAction(js); textbox.Actions.Format = jsAction; pdf.Form.Fields.Add(textbox); pdf.SaveToFile("FormatField.pdf", FileFormat.PDF); } } }
Imports Spire.Pdf Imports Spire.Pdf.Actions Imports Spire.Pdf.Fields Imports System.Drawing Namespace FormatTextboxField Class Program Private Shared Sub Main(args As String()) Dim pdf As New PdfDocument() Dim page As PdfPageBase = pdf.Pages.Add() Dim textbox As New PdfTextBoxField(page, "Number-TextBox") textbox.Bounds = New RectangleF(10, 10, 100, 20) textbox.BorderWidth = 0.75F textbox.BorderStyle = PdfBorderStyle.Solid Dim js As String = PdfJavaScript.GetNumberKeystrokeString(2, 0, 0, 0, "$", True) Dim jsAction As New PdfJavaScriptAction(js) textbox.Actions.KeyPressed = jsAction js = PdfJavaScript.GetNumberFormatString(2, 0, 0, 0, "$", True) jsAction = New PdfJavaScriptAction(js) textbox.Actions.Format = jsAction pdf.Form.Fields.Add(textbox) pdf.SaveToFile("FormatField.pdf", FileFormat.PDF) End Sub End Class End Namespace
Add Tooltip for PDF Form Field in C#/VB.NET
Tooltip is a message box that appears when users hover the pointer over the form field, providing users with instructions about the field, for instance, some extra information that users may find helpful in filling in the form field. This article presents how to add a tooltip to PDF form field using Spire.PDF in C# and VB.NET.
Code Snippet
Step 1: Initialize a new object of PdfDcoument class, add a page to it.
PdfDocument doc = new PdfDocument(); PdfPageBase page = doc.Pages.Add(PdfPageSize.A4, new PdfMargins(0));
Step 2: Add some text and a textbox on the PDF page.
PdfFont font = new PdfFont(PdfFontFamily.Helvetica, 12f,PdfFontStyle.Bold); PdfBrush brush = PdfBrushes.Black; float x = 50; float y = 50; float tempX = 0; string text = "E-mail: "; page.Canvas.DrawString(text, font, brush, x, y); tempX = font.MeasureString(text).Width + x+15; PdfTextBoxField textbox = new PdfTextBoxField(page, "TextBox"); textbox.Bounds = new RectangleF(tempX, y, 100, 15); textbox.BorderWidth = 0.75f; textbox.BorderStyle = PdfBorderStyle.Solid; doc.Form.Fields.Add(textbox);
Step 3: The PdfDocument class provides a Fields collection which represents all form fields in the PDF document. You can get the specific field by its index or name, then set the value of ToolTip property to add a tooltip.
doc.Form.Fields["TextBox"].ToolTip = "Please insert a valid email address";
Step 4: Save and launch the file.
doc.SaveToFile("sample.pdf", FileFormat.PDF); System.Diagnostics.Process.Start("sample.pdf");
Output:
Full Code:
using Spire.Pdf; using Spire.Pdf.Fields; using Spire.Pdf.Graphics; using System.Drawing; namespace AddTooltip { class Program { static void Main(string []args) { PdfDocument doc = new PdfDocument(); PdfPageBase page = doc.Pages.Add(PdfPageSize.A4, new PdfMargins(0)); PdfFont font = new PdfFont(PdfFontFamily.Helvetica, 12f, PdfFontStyle.Bold); PdfBrush brush = PdfBrushes.Black; float x = 50; float y = 50; float tempX = 0; string text = "E-mail: "; page.Canvas.DrawString(text, font, brush, x, y); tempX = font.MeasureString(text).Width + x + 15; PdfTextBoxField textbox = new PdfTextBoxField(page, "TextBox"); textbox.Bounds = new RectangleF(tempX, y, 100, 15); textbox.BorderWidth = 0.75f; textbox.BorderStyle = PdfBorderStyle.Solid; doc.Form.Fields.Add(textbox); doc.Form.Fields["TextBox"].ToolTip = "Please insert a valid email address"; doc.SaveToFile("sample.pdf", FileFormat.PDF); System.Diagnostics.Process.Start("sample.pdf"); } } }
Imports Spire.Pdf Imports Spire.Pdf.Fields Imports Spire.Pdf.Graphics Imports System.Drawing Namespace AddTooltip Class Program Private Shared Sub Main(args As String()) Dim doc As New PdfDocument() Dim page As PdfPageBase = doc.Pages.Add(PdfPageSize.A4, New PdfMargins(0)) Dim font As New PdfFont(PdfFontFamily.Helvetica, 12F, PdfFontStyle.Bold) Dim brush As PdfBrush = PdfBrushes.Black Dim x As Single = 50 Dim y As Single = 50 Dim tempX As Single = 0 Dim text As String = "E-mail: " page.Canvas.DrawString(text, font, brush, x, y) tempX = font.MeasureString(text).Width + x + 15 Dim textbox As New PdfTextBoxField(page, "TextBox") textbox.Bounds = New RectangleF(tempX, y, 100, 15) textbox.BorderWidth = 0.75F textbox.BorderStyle = PdfBorderStyle.Solid doc.Form.Fields.Add(textbox) doc.Form.Fields("TextBox").ToolTip = "Please insert a valid email address" doc.SaveToFile("sample.pdf", FileFormat.PDF) System.Diagnostics.Process.Start("sample.pdf") End Sub End Class End Namespace