FormField

FormField (15)

Monday, 21 August 2017 07:54

Remove/Delete Form Fields from PDF in C#

Written by support iceblue

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/Delete Form Fields from PDF in C#

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.

//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/Delete Form Fields from PDF in C#

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.

//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");

Remove/Delete Form Fields from PDF 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:

Assign an Icon to a PDF Button Field and Set Icon Layout in C#

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");            
        }
    }
}

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");

Set

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");
}

Set

Tuesday, 21 March 2017 07:34

Working with FDF and XFDF Files

Written by support iceblue

Spire.PDF allows importing FDF, XFDF files to PDF forms as well as exporting PDF forms data to FDF, XFDF files.

The below code examples illustrate how to implement the above features using Spire.PDF.

Importing FDF/ XFDF to PDF

To import FDF/XFDF file to PDF, we can use the ImportData method in the PdfFormWidget class:

//Load the PDF document
PdfDocument document = new PdfDocument("Import.pdf");

//Load the existing forms 
PdfFormWidget loadedForm = document.Form as PdfFormWidget;

//Import FDF to PDF
loadedForm.ImportData("ImportFDF.fdf", DataFormat.Fdf);

//Import XFDF to PDF
//loadedForm.ImportData("ImportXFDF.xfdf", DataFormat.XFdf);

//Save the document
document.SaveToFile("Output.pdf");

//Close the document
document.Close();

Exporting PDF Forms Data to FDF/XFDF

To export PDF forms data to FDF/XFDF file, we can use the ExportData method in the PdfFormWidget class:

// Load the PDF document
PdfDocument document = new PdfDocument("Export.pdf");

//Load the existing forms 
PdfFormWidget loadedForm = document.Form as PdfFormWidget;

//Export the first form to FDF
PdfField field = loadedForm.FieldsWidget.List[0] as PdfField;
loadedForm.ExportData("ExportFDF.fdf", DataFormat.Fdf, field.Name);

//Export the first form to XFDF
//loadedForm.ExportData("ExportXFDF.xfdf", DataFormat.XFdf, field.Name);

//Close the document
document.Close();
Thursday, 16 February 2017 09:07

How to Flatten PDF Form Fields in C#, VB.NET

Written by support iceblue

Flattening form fields is an efficient way to prevent other users from editing or deleting the information filled in PDF forms. After flattening, the filled in values (text) will remain visible in the document but the form fields will no longer be editable. This article presents how to flatten all the form fields in a PDF document by using Spire.PDF.

Below pdf file contains two form fields that are already filled with contents:

How to Flatten PDF Form Fields in C#, VB.NET

Refer to below code snippets to flatten the form fields:

Step 1: Instatiate an object of PdfDocument class and load the PDF document.

PdfDocument pdf = new PdfDocument();
pdf.LoadFromFile("Form.pdf");

Step 2: Set the IsFlatten property as true to flatten all the form fields in the document.

pdf.Form.IsFlatten = true;

Step 3: Save the document.

pdf.SaveToFile("Flatten.pdf");

Screenshot after flattening:

How to Flatten PDF Form Fields in C#, VB.NET

Full code:

[C#]
using Spire.Pdf;

namespace Flatten_PDF_Form_Fields
{
    class Program
    {
        static void Main(string[] args)
        {
            PdfDocument pdf = new PdfDocument();
            pdf.LoadFromFile("Form.pdf");
            pdf.Form.IsFlatten = true;
            pdf.SaveToFile("Flatten.pdf");
        }
    }
}
[VB.NET]
Imports Spire.Pdf

Namespace Flatten_PDF_Form_Fields
	Class Program
		Private Shared Sub Main(args As String())
			Dim pdf As New PdfDocument()
			pdf.LoadFromFile("Form.pdf")
			pdf.Form.IsFlatten = True
			pdf.SaveToFile("Flatten.pdf")
		End Sub
	End Class
End Namespace
Tuesday, 14 February 2017 07:54

How to Fill XFA Form Fields in C#, VB.NET

Written by support iceblue

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:

How to Fill XFA Form Fields in C#, VB.NET

Full Code:

[C#]
PdfDocument doc = new PdfDocument();
doc.LoadFromFile("DynamicXFA.pdf");

PdfFormWidget formWidget = doc.Form as PdfFormWidget;   
List<XfaField> 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);
[VB.NET]
Dim doc As New PdfDocument()
doc.LoadFromFile("DynamicXFA.pdf")

Dim formWidget As PdfFormWidget = TryCast(doc.Form, PdfFormWidget)
Dim xfaFields 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)

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:

How to Detect the Required Form Field in PDF in C#, VB.NET

Full Code:

[C#]
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]
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()
Thursday, 08 September 2016 02:11

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

Written by support iceblue

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()

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:

How to Format Textbox Field using JavaScript in C#, VB.NET

Full Code:

[C#]
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);
[VB.NET]
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)

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:

Add Tooltip for PDF Form Field in C#, VB.NET

Full Code:

[C#]
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");
[VB.NET]
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")
Page 1 of 2