With the help of Spire.PDF, developers can easily add new text to the PDF; create form fields to both the new and existing PDF file. Spire.PDF also owns the ability to set the text formatting for the PDF fields' area. This article will show you how to set the font and color for PDF Combo Box field by the method of PdfComboBoxField.

Note: Before Start, please download the latest version of Spire.PDF and add Spire.PDF.dll in the bin folder as the reference of Visual Studio.

Here comes to the details:

Step 1: Create a new PDF document.

PdfDocument doc = new PdfDocument();

Step 2: Add a new page to the PDF document and set the page size for the page.

PdfPageBase page = doc.Pages.Add(PdfPageSize.A4, new PdfMargins());

Step 3: Draw the text to the PDF page and set the location, font and color for the text.

PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial", 10f, FontStyle.Bold));
RectangleF labelBounds = new RectangleF(20, 20, 40, font.Height);
page.Canvas.DrawString("My label", font, PdfBrushes.Black, labelBounds);

Step 4: Create a Combo Box and add value for it. Use comboBox.Font and comboBox.ForeColor to set the font and color for the text on Combo Box area.

PdfComboBoxField comboBox = new PdfComboBoxField(page, "cmb");
comboBox.Bounds = new RectangleF(80, 20, 80, font.Height);
comboBox.Font = font;
comboBox.ForeColor = Color.Blue;
comboBox.Items.Add(new PdfListFieldItem("value 1", "text 1"));
comboBox.Items.Add(new PdfListFieldItem("value 2", "text 2"));
comboBox.Items.Add(new PdfListFieldItem("value 3", "text 3"));

Step 5: Add the Combo Box to the PDF file.

doc.Form.Fields.Add(comboBox);

Step 6: Save the document to file and launch to preview it.

string file = string.Format("result.pdf", Guid.NewGuid().ToString());
doc.SaveToFile(file);
System.Diagnostics.Process.Start(file);

Effective screenshot after setting the font and color for text on the Combo Box area:

How to set the font and color for the text on PDF Combo Box field area

Full codes:

using Spire.Pdf;
using Spire.Pdf.Fields;
using Spire.Pdf.Graphics;
using System;
using System.Drawing;


namespace SetFontColorInComboboxField
{
    class Program
    {
        static void Main(string []args)
        {
            PdfDocument doc = new PdfDocument();

            PdfPageBase page = doc.Pages.Add(PdfPageSize.A4, new PdfMargins());

            PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial", 10f, FontStyle.Bold));
            RectangleF labelBounds = new RectangleF(20, 20, 40, font.Height);
            page.Canvas.DrawString("My label", font, PdfBrushes.Black, labelBounds);

            PdfComboBoxField comboBox = new PdfComboBoxField(page, "cmb");
            comboBox.Bounds = new RectangleF(80, 20, 80, font.Height);
            comboBox.Font = font;
            comboBox.ForeColor = Color.Blue;
            comboBox.Items.Add(new PdfListFieldItem("value 1", "text 1"));
            comboBox.Items.Add(new PdfListFieldItem("value 2", "text 2"));
            comboBox.Items.Add(new PdfListFieldItem("value 3", "text 3"));

            doc.Form.Fields.Add(comboBox);

            string file = string.Format("result.pdf", Guid.NewGuid().ToString());
            doc.SaveToFile(file);
            System.Diagnostics.Process.Start(file);
        }
    }
}
Published in Form Field

PDF form is often used to display, catch and edit data. People can fill blanks with data and submit data to server. Spire.PDF now enables users to add fields and create form in existing PDF document.

Here are the steps:

Step 1: Create PDF document, and load a blank PDF file, then get the first page.

PdfDocument pdf = new PdfDocument("Blank.pdf");
pdf.AllowCreateForm = (pdf.Form == null) ? true : false;
PdfPageBase page = pdf.Pages[0];

Step 2: Set font and font color. Preset coordinate.

PdfFont font = new PdfFont(PdfFontFamily.Helvetica, 13f);
PdfBrush brush = PdfBrushes.Black;
float x = 10;
float y = 10;
float tempX = 0;
float tempY = 0;

Step 3: Draw textbox.

string text = "Textbox: ";
page.Canvas.DrawString(text, font, brush, x, y);
tempX = font.MeasureString(text).Width + 15;
tempY = font.MeasureString(text).Height + 15;
PdfTextBoxField textbox = new PdfTextBoxField(page, "TextBox");
textbox.Bounds = new RectangleF(tempX, y, tempX * 2, 15);
textbox.BorderWidth = 0.75f;
textbox.BorderStyle = PdfBorderStyle.Solid;
pdf.Form.Fields.Add(textbox);

Step 4: Draw checkbox.

text = "Checkbox: ";
y += tempY;
page.Canvas.DrawString(text, font, brush, x, y);
tempX = font.MeasureString(text).Width + 15;
tempY = font.MeasureString(text).Height + 15;
PdfCheckBoxField checkbox = new PdfCheckBoxField(page, "CheckBox");
checkbox.Bounds = new RectangleF(tempX, y, 15, 15);
checkbox.BorderWidth = 0.75f;
checkbox.Style = PdfCheckBoxStyle.Cross;
pdf.Form.Fields.Add(checkbox);

Step 5: Draw Listbox and add content.

//ListBox
text = "Listbox: ";
y += tempY;
page.Canvas.DrawString(text, font, brush, x, y);
tempX = font.MeasureString(text).Width + 15;
tempY = font.MeasureString(text).Height + 15;
PdfListBoxField listbox = new PdfListBoxField(page, "ListBox");
listbox.Bounds = new RectangleF(tempX, y, tempX * 2, tempY * 2);
listbox.BorderWidth = 0.75f;
for (int i = 0; i < 3; i++)
{
     string tempText = string.Format("Text {0}", i);
     string tempValue = string.Format("Value {0}", i);
     listbox.Items.Add(new PdfListFieldItem(tempText, tempValue));
}
pdf.Form.Fields.Add(listbox);

Step 6: Draw RadioButton.

//RadioButton
text = "Radiobutton: ";
y += tempY * 2 + 15;
page.Canvas.DrawString(text, font, brush, x, y);
tempX = font.MeasureString(text).Width + 15;
tempY = font.MeasureString(text).Height + 15;
PdfRadioButtonListField radiobutton = new PdfRadioButtonListField(page, "RadioButton");
for (int i = 0; i < 3; i++)
{
     PdfRadioButtonListItem item = new PdfRadioButtonListItem(string.Format("rb{0}", i));
     item.BorderWidth = 0.75f;
     item.Bounds = new RectangleF(tempX + i * 20, y, 15, 15);
     radiobutton.Items.Add(item);
}
pdf.Form.Fields.Add(radiobutton);

Step 7: Draw combobox and add content.

//ComboBox
text = "ComboBox: ";
y += tempY;
page.Canvas.DrawString(text, font, brush, x, y);
tempX = font.MeasureString(text).Width + 15;
tempY = font.MeasureString(text).Height + 15;
PdfComboBoxField combobox = new PdfComboBoxField(page, "ComboBox");
combobox.Bounds = new RectangleF(tempX, y, tempX, 15);
combobox.BorderWidth = 0.75f;
for (int i = 0; i < 3; i++)
{
    string tempText = string.Format("Text {0}", i);
    string tempValue = string.Format("Value {0}", i);
    combobox.Items.Add(new PdfListFieldItem(tempText, tempValue));
}
pdf.Form.Fields.Add(combobox);

Step 8: Save and review

loDoc.SaveToFile("result.pdf");
System.Diagnostics.Process.Start("result.pdf");

Result screenshot:

How to add form field to an existing PDF via Spire.PDF

Full Code:

using Spire.Pdf;
using Spire.Pdf.Fields;
using Spire.Pdf.Graphics;
using System.Drawing;


namespace AddFormFieldToExistingPDF
{
    class Program
    {
        static void Main(string []args)
        {
            PdfDocument pdf = new PdfDocument("Blank.pdf");
            pdf.AllowCreateForm = (pdf.Form == null) ? true : false;
            PdfPageBase page = pdf.Pages[0];


            PdfFont font = new PdfFont(PdfFontFamily.Helvetica, 13f);
            PdfBrush brush = PdfBrushes.Black;
            float x = 10;
            float y = 10;
            float tempX = 0;
            float tempY = 0;

            //TextBox
            string text = "Textbox: ";
            page.Canvas.DrawString(text, font, brush, x, y);
            tempX = font.MeasureString(text).Width + 15;
            tempY = font.MeasureString(text).Height + 15;
            PdfTextBoxField textbox = new PdfTextBoxField(page, "TextBox");
            textbox.Bounds = new RectangleF(tempX, y, tempX * 2, 15);
            textbox.BorderWidth = 0.75f;
            textbox.BorderStyle = PdfBorderStyle.Solid;
            pdf.Form.Fields.Add(textbox);

            //CheckBox
            text = "Checkbox: ";
            y += tempY;
            page.Canvas.DrawString(text, font, brush, x, y);
            tempX = font.MeasureString(text).Width + 15;
            tempY = font.MeasureString(text).Height + 15;
            PdfCheckBoxField checkbox = new PdfCheckBoxField(page, "CheckBox");
            checkbox.Bounds = new RectangleF(tempX, y, 15, 15);
            checkbox.BorderWidth = 0.75f;
            checkbox.Style = PdfCheckBoxStyle.Cross;
            pdf.Form.Fields.Add(checkbox);

            //ListBox
            text = "Listbox: ";
            y += tempY;
            page.Canvas.DrawString(text, font, brush, x, y);
            tempX = font.MeasureString(text).Width + 15;
            tempY = font.MeasureString(text).Height + 15;
            PdfListBoxField listbox = new PdfListBoxField(page, "ListBox");
            listbox.Bounds = new RectangleF(tempX, y, tempX * 2, tempY * 2);
            listbox.BorderWidth = 0.75f;
            for (int i = 0; i < 3; i++)
            {
                string tempText = string.Format("Text {0}", i);
                string tempValue = string.Format("Value {0}", i);
                listbox.Items.Add(new PdfListFieldItem(tempText, tempValue));
            }
            pdf.Form.Fields.Add(listbox);

            //RadioButton
            text = "Radiobutton: ";
            y += tempY * 2 + 15;
            page.Canvas.DrawString(text, font, brush, x, y);
            tempX = font.MeasureString(text).Width + 15;
            tempY = font.MeasureString(text).Height + 15;
            PdfRadioButtonListField radiobutton = new PdfRadioButtonListField(page, "RadioButton");
            for (int i = 0; i < 3; i++)
            {
                PdfRadioButtonListItem item = new PdfRadioButtonListItem(string.Format("rb{0}", i));
                item.BorderWidth = 0.75f;
                item.Bounds = new RectangleF(tempX + i * 20, y, 15, 15);
                radiobutton.Items.Add(item);
            }
            pdf.Form.Fields.Add(radiobutton);

            //ComboBox
            text = "ComboBox: ";
            y += tempY;
            page.Canvas.DrawString(text, font, brush, x, y);
            tempX = font.MeasureString(text).Width + 15;
            tempY = font.MeasureString(text).Height + 15;
            PdfComboBoxField combobox = new PdfComboBoxField(page, "ComboBox");
            combobox.Bounds = new RectangleF(tempX, y, tempX, 15);
            combobox.BorderWidth = 0.75f;
            for (int i = 0; i < 3; i++)
            {
                string tempText = string.Format("Text {0}", i);
                string tempValue = string.Format("Value {0}", i);
                combobox.Items.Add(new PdfListFieldItem(tempText, tempValue));
            }
            pdf.Form.Fields.Add(combobox);

            pdf.SaveToFile("Result.pdf");
            System.Diagnostics.Process.Start("Result.pdf");
        }
    }
}
Published in Form Field
Tuesday, 11 November 2014 07:56

Set all fields on a form to read only

Form field has been widely used by developers to display, catch and edit data. Developers may create a form to let others to fill the data and then save the form as a non-fillable file and set it to read only. Spire.PDF supports to create and fill form field; this article will focus on show you how to change the field's value and set all the fields on a form to read only.

By using the PdfFormWidget class, we can get the PDF field collection on the form and then update the values on it. Here comes to the code snippet of how to change the form field's value and set it to read only:

Step 1: Create PDFDocument and load from file.

PdfDocument doc = new PdfDocument();
doc.LoadFromFile("FormField.pdf");

Step 2: Get the PDF field collection on the Form.

PdfFormWidget widget = doc.Form as PdfFormWidget;

Step 3: Traverse each PDF field in pdf field collection.

for (int i = 0; i < widget.FieldsWidget.List.Count; i++)
  {
    PdfField f = widget.FieldsWidget.List[i] as PdfField;

Step 4: Find a PDF field named username and set the value for it.

if (f.Name == "username")
{
  //Convert the pdf field to PdfTextBoxFieldWidget
PdfTextBoxFieldWidget textboxField = f as PdfTextBoxFieldWidget;
  //Change its text
textboxField.Text = "Sky.Luo";
                }

Step 5: Set the field to read-only.

f.Flatten = true;
f.ReadOnly = true;

Step 6: Save the document to file and launch to view it.

doc.SaveToFile("FormFieldEdit.pdf");
System.Diagnostics.Process.Start("FormFieldEdit.pdf");

Effective screenshot of the read only form field:

How to set all fields on a form to read only

Full codes:

using Spire.Pdf;
using Spire.Pdf.Fields;
using Spire.Pdf.Widget;

namespace ReadOnlyField
{
    class Program
    {
        static void Main(string []args)
        {
            PdfDocument doc = new PdfDocument();
            doc.LoadFromFile("FormField.pdf");

            PdfFormWidget widget = doc.Form as PdfFormWidget;

            for (int i = 0; i < widget.FieldsWidget.List.Count; i++)
            {
                PdfField f = widget.FieldsWidget.List[i] as PdfField;
                if (f.Name == "username")
                {
                    PdfTextBoxFieldWidget textboxField = f as PdfTextBoxFieldWidget;
                    textboxField.Text = "Sky.Luo";
                }
                f.Flatten = true;
                f.ReadOnly = true;
            }
            doc.SaveToFile("FormFieldEdit.pdf");
            System.Diagnostics.Process.Start("FormFieldEdit.pdf");
            
        }
    }
}
Published in Form Field
Thursday, 09 January 2014 02:47

Fill Form Fields in PDF File in C#

We have already demonstrated how to create form fields in PDF file. This article mainly shows you how developers fill form field in PDF in C# only with 3 simple steps by using a standalone .NET PDF component Spire.PDF.

Make sure Spire.PDF for .NET has been installed correctly and then add Spire.Pdf.dll as reference in the downloaded Bin folder though the below path: "..\Spire.Pdf\Bin\NET4.0\ Spire.Pdf.dll". Here comes to the details of how developers Fill Form Fields by using Spire.PDF:

Step 1: Open the form that needs to fill the data

[C#]
//Create a pdf document
PdfDocument doc = new PdfDocument();
//Load from file
doc.LoadFromFile(@"..\..\FormField.pdf");

Step 2: Update the data to the form

[C#]
//Get form
PdfFormWidget formWidget = doc.Form as PdfFormWidget;
for (int i = 0; i < formWidget.FieldsWidget.List.Count; i++)
            {
                PdfField field = formWidget.FieldsWidget.List[i] as PdfField;


//Fill the data for textBoxField
if (field is PdfTextBoxFieldWidget)
   {
    PdfTextBoxFieldWidget textBoxField = field as PdfTextBoxFieldWidget;
    switch (textBoxField.Name)
     {

     case "email":
        textBoxField.Text = "support@e-iceblue.com";
    break;
     case "password":
        textBoxField.Password = true;
        textBoxField.Text = "e-iceblue";

//Fill the data for listBoxField
if (field is PdfListBoxWidgetFieldWidget)
  {
     PdfListBoxWidgetFieldWidget listBoxField = field as PdfListBoxWidgetFieldWidget;
     switch (listBoxField.Name)
       {

        case "email_format":
         int[] index = { 1 };
         listBoxField.SelectedIndex = index;
         break;


//Fill the data for comBoxField
if (field is PdfComboBoxWidgetFieldWidget)
  {
   PdfComboBoxWidgetFieldWidget comBoxField = field as PdfComboBoxWidgetFieldWidget;
   switch (comBoxField.Name)
    {

     case "title":
       int[] items = { 0 };
       comBoxField.SelectedIndex = items;
       break;


//Fill the data for checkBoxField
if (field is PdfCheckBoxWidgetFieldWidget)
  {
   PdfCheckBoxWidgetFieldWidget checkBoxField = field as PdfCheckBoxWidgetFieldWidget;
   switch (checkBoxField.Name)
    {

    case "agreement_of_terms":
      checkBoxField.Checked = true;
      break;

Step 3: Save and launch file

[C#]
//Save the document to file in PDF format
doc.SaveToFile(@"../../FormFieldData.pdf.pdf");
//Launch the file
System.Diagnostics.Process.Start(@"../../FormFieldData.pdf.pdf");

Effective Screenshot:

The original PDF with form fields:

before fill form fields

After fill the form fields:

after fill form fields

View the full code as below:

C#
using Spire.Pdf;
using Spire.Pdf.Fields;
using Spire.Pdf.Widget;


namespace FillFormFields
{
    class Program
    {
        static void Main(string []args){
            PdfDocument doc = new PdfDocument();
            doc.LoadFromFile(@"..\..\FormField.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;
                if (field is PdfTextBoxFieldWidget)
                {
                    PdfTextBoxFieldWidget textBoxField = field as PdfTextBoxFieldWidget;
                    switch (textBoxField.Name)
                    {
                        case "email":
                            textBoxField.Text = "support@e-iceblue.com";
                            break;
                        case "username":
                            textBoxField.Text = "E-iceblue";
                            break;
                        case "password":
                            textBoxField.Password = true;
                            textBoxField.Text = "e-iceblue";
                            break;
                        case "password2":
                            textBoxField.Password = true;
                            textBoxField.Text = "e-iceblue";
                            break;
                        case "company_name ":
                            textBoxField.Text = "E-iceblue";
                            break;
                        case "first_name":
                            textBoxField.Text = "James";
                            break;
                        case "last_name":
                            textBoxField.Text = "Chen";
                            break;
                        case "middle_name":
                            textBoxField.Text = "J";
                            break;
                        case "address1":
                            textBoxField.Text = "Chengdu";
                            break;
                        case "address2":
                            textBoxField.Text = "Beijing";
                            break;
                        case "city":
                            textBoxField.Text = "Shanghai";
                            break;
                        case "postal_code":
                            textBoxField.Text = "11111";
                            break;
                        case "state":
                            textBoxField.Text = "Shanghai";
                            break;
                        case "phone":
                            textBoxField.Text = "1234567901";
                            break;
                        case "mobile_phone":
                            textBoxField.Text = "123456789";
                            break;
                        case "fax":
                            textBoxField.Text = "12121212";
                            break;
                    }
                }
                if (field is PdfListBoxWidgetFieldWidget)
                {
                    PdfListBoxWidgetFieldWidget listBoxField = field as PdfListBoxWidgetFieldWidget;
                    switch (listBoxField.Name)
                    {
                        case "email_format":
                            int[] index = { 1 };
                            listBoxField.SelectedIndex = index;
                            break;
                    }
                }

                if (field is PdfComboBoxWidgetFieldWidget)
                {
                    PdfComboBoxWidgetFieldWidget comBoxField = field as PdfComboBoxWidgetFieldWidget;
                    switch (comBoxField.Name)
                    {
                        case "title":
                            int[] items = { 0 };
                            comBoxField.SelectedIndex = items;
                            break;
                    }
                }

                if (field is PdfRadioButtonListFieldWidget)
                {
                    PdfRadioButtonListFieldWidget radioBtnField = field as PdfRadioButtonListFieldWidget;
                    switch (radioBtnField.Name)
                    {
                        case "country":
                            radioBtnField.SelectedIndex = 1;
                            break;
                    }
                }

                if (field is PdfCheckBoxWidgetFieldWidget)
                {
                    PdfCheckBoxWidgetFieldWidget checkBoxField = field as PdfCheckBoxWidgetFieldWidget;
                    switch (checkBoxField.Name)
                    {
                        case "agreement_of_terms":
                            checkBoxField.Checked = true;
                            break;
                    }
                }
                if (field is PdfButtonWidgetFieldWidget)
                {
                    PdfButtonWidgetFieldWidget btnField = field as PdfButtonWidgetFieldWidget;
                    switch (btnField.Name)
                    {
                        case "submit":
                            btnField.Text = "Submit";
                            break;
                    }
                }
            }
            doc.SaveToFile(@"../../FormFieldData.pdf.pdf");
            System.Diagnostics.Process.Start(@"../../FormFieldData.pdf.pdf");
        }
    }
}
VB.NET
Imports Spire.Pdf
Imports Spire.Pdf.Fields
Imports Spire.Pdf.Widget


Namespace FillFormFields
	Class Program
		Private Shared Sub Main(args As String())
			Dim doc As New PdfDocument()
			doc.LoadFromFile("..\..\FormField.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)
				If TypeOf field Is PdfTextBoxFieldWidget Then
					Dim textBoxField As PdfTextBoxFieldWidget = TryCast(field, PdfTextBoxFieldWidget)
					Select Case textBoxField.Name
						Case "email"
							textBoxField.Text = "support@e-iceblue.com"
							Exit Select
						Case "username"
							textBoxField.Text = "E-iceblue"
							Exit Select
						Case "password"
							textBoxField.Password = True
							textBoxField.Text = "e-iceblue"
							Exit Select
						Case "password2"
							textBoxField.Password = True
							textBoxField.Text = "e-iceblue"
							Exit Select
						Case "company_name "
							textBoxField.Text = "E-iceblue"
							Exit Select
						Case "first_name"
							textBoxField.Text = "James"
							Exit Select
						Case "last_name"
							textBoxField.Text = "Chen"
							Exit Select
						Case "middle_name"
							textBoxField.Text = "J"
							Exit Select
						Case "address1"
							textBoxField.Text = "Chengdu"
							Exit Select
						Case "address2"
							textBoxField.Text = "Beijing"
							Exit Select
						Case "city"
							textBoxField.Text = "Shanghai"
							Exit Select
						Case "postal_code"
							textBoxField.Text = "11111"
							Exit Select
						Case "state"
							textBoxField.Text = "Shanghai"
							Exit Select
						Case "phone"
							textBoxField.Text = "1234567901"
							Exit Select
						Case "mobile_phone"
							textBoxField.Text = "123456789"
							Exit Select
						Case "fax"
							textBoxField.Text = "12121212"
							Exit Select
					End Select
				End If
				If TypeOf field Is PdfListBoxWidgetFieldWidget Then
					Dim listBoxField As PdfListBoxWidgetFieldWidget = TryCast(field, PdfListBoxWidgetFieldWidget)
					Select Case listBoxField.Name
						Case "email_format"
							Dim index As Integer() = {1}
							listBoxField.SelectedIndex = index
							Exit Select
					End Select
				End If

				If TypeOf field Is PdfComboBoxWidgetFieldWidget Then
					Dim comBoxField As PdfComboBoxWidgetFieldWidget = TryCast(field, PdfComboBoxWidgetFieldWidget)
					Select Case comBoxField.Name
						Case "title"
							Dim items As Integer() = {0}
							comBoxField.SelectedIndex = items
							Exit Select
					End Select
				End If

				If TypeOf field Is PdfRadioButtonListFieldWidget Then
					Dim radioBtnField As PdfRadioButtonListFieldWidget = TryCast(field, PdfRadioButtonListFieldWidget)
					Select Case radioBtnField.Name
						Case "country"
							radioBtnField.SelectedIndex = 1
							Exit Select
					End Select
				End If

				If TypeOf field Is PdfCheckBoxWidgetFieldWidget Then
					Dim checkBoxField As PdfCheckBoxWidgetFieldWidget = TryCast(field, PdfCheckBoxWidgetFieldWidget)
					Select Case checkBoxField.Name
						Case "agreement_of_terms"
							checkBoxField.Checked = True
							Exit Select
					End Select
				End If
				If TypeOf field Is PdfButtonWidgetFieldWidget Then
					Dim btnField As PdfButtonWidgetFieldWidget = TryCast(field, PdfButtonWidgetFieldWidget)
					Select Case btnField.Name
						Case "submit"
							btnField.Text = "Submit"
							Exit Select
					End Select
				End If
			Next
			doc.SaveToFile("../../FormFieldData.pdf.pdf")
			System.Diagnostics.Process.Start("../../FormFieldData.pdf.pdf")
		End Sub
	End Class
End Namespace
Published in Form Field

The ability to create fillable PDF forms that end users can fill out (without having to print) can be a real benefit to making your business efficient. With these documents, users can download them, fill them out, save them, and send them back to you. No more printing and scanning. In this article, you will learn how to create, fill, or remove fillable forms in PDF in C# and VB.NET by using Spire.PDF for .NET.

Spire.PDF for .NET offers a series of useful classes under the Spire.Pdf.Fields namespace, allowing programmers to create and edit various types of form fields including text box, check box, combo box, list box, and radio button. The table below lists some of the core classes involved in this tutorial.

Class Description
PdfForm Represents interactive form of the PDF document.
PdfField Represents field of the PDF document's interactive form.
PdfTextBoxField Represents text box field in the PDF form.
PdfCheckBoxField Represents check box field in the PDF form.
PdfComboBoxField Represents combo box field in the PDF Form.
PdfListBoxField Represents list box field of the PDF form.
PdfListFieldItem Represents an item of a list field.
PdfRadioButtonListField Represents radio button field in the PDF form.
PdfRadioButtonListItem Represents an item of a radio button list.
PdfButtonField Represents button field in the PDF form.
PdfSignatureField Represents signature field in the PDF form.

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

Create Fillable Form Fields in a PDF Document

To create a PDF form, initialize an instance of the corresponding field class. Set its size and position in the document through the Bounds property, and then add it to PDF using PdfFormFieldCollection.Add() method. The following are the main steps to create various types of form fields in a PDF document using Spire.PDF for .NET.

  • Create a PdfDocument object.
  • Add a page using PdfDocuemnt.Pages.Add() method.
  • Create a PdfTextBoxField object, set the properties of the field including Bounds, Font and Text, and then add it to the document using PdfFormFieldCollection.Add() method.
  • Repeat the step 3 to add check box, combo box, list box, radio button, signature field and button to the document.
  • Save the document to a PDF file using PdfDocument.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Pdf;
using Spire.Pdf.Actions;
using Spire.Pdf.Fields;
using Spire.Pdf.Graphics;
using System.Drawing;

namespace CreateFillableFormsInPdf
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a PdfDocument object
            PdfDocument doc = new PdfDocument();

            //Add a page
            PdfPageBase page = doc.Pages.Add();

            //Initialize x and y coordinates
            float baseX = 100;
            float baseY = 30;

            //Create two brush objects
            PdfSolidBrush brush1 = new PdfSolidBrush(new PdfRGBColor(Color.Blue));
            PdfSolidBrush brush2 = new PdfSolidBrush(new PdfRGBColor(Color.Black));

            //Create a font 
            PdfFont font = new PdfFont(PdfFontFamily.TimesRoman, 12f, PdfFontStyle.Regular);

            //Add a textbox 
            page.Canvas.DrawString("TextBox:", font, brush1, new PointF(10, baseY));
            RectangleF tbxBounds = new RectangleF(baseX, baseY, 150, 15);
            PdfTextBoxField textBox = new PdfTextBoxField(page, "textbox");
            textBox.Bounds = tbxBounds;
            textBox.Text = "Hello World";
            textBox.Font = font;
            doc.Form.Fields.Add(textBox);
            baseY += 25;

            //add two checkboxes 
            page.Canvas.DrawString("CheckBox:", font, brush1, new PointF(10, baseY));
            RectangleF checkboxBound1 = new RectangleF(baseX, baseY, 15, 15);
            PdfCheckBoxField checkBoxField1 = new PdfCheckBoxField(page, "checkbox1");
            checkBoxField1.Bounds = checkboxBound1;
            checkBoxField1.Checked = false;
            page.Canvas.DrawString("Option 1", font, brush2, new PointF(baseX + 20, baseY));

            RectangleF checkboxBound2 = new RectangleF(baseX + 70, baseY, 15, 15);
            PdfCheckBoxField checkBoxField2 = new PdfCheckBoxField(page, "checkbox2");
            checkBoxField2.Bounds = checkboxBound2;
            checkBoxField2.Checked = false;
            page.Canvas.DrawString("Option 2", font, brush2, new PointF(baseX + 90, baseY));
            doc.Form.Fields.Add(checkBoxField1);
            doc.Form.Fields.Add(checkBoxField2);
            baseY += 25;

            //Add a listbox
            page.Canvas.DrawString("ListBox:", font, brush1, new PointF(10, baseY));
            RectangleF listboxBound = new RectangleF(baseX, baseY, 150, 50);
            PdfListBoxField listBoxField = new PdfListBoxField(page, "listbox");
            listBoxField.Items.Add(new PdfListFieldItem("Item 1", "item1"));
            listBoxField.Items.Add(new PdfListFieldItem("Item 2", "item2"));
            listBoxField.Items.Add(new PdfListFieldItem("Item 3", "item3")); ;
            listBoxField.Bounds = listboxBound;
            listBoxField.Font = font;
            listBoxField.SelectedIndex = 0;
            doc.Form.Fields.Add(listBoxField);
            baseY += 60;

            //Add two radio buttons
            page.Canvas.DrawString("RadioButton:", font, brush1, new PointF(10, baseY));
            PdfRadioButtonListField radioButtonListField = new PdfRadioButtonListField(page, "radio");
            PdfRadioButtonListItem radioItem1 = new PdfRadioButtonListItem("option1");
            RectangleF radioBound1 = new RectangleF(baseX, baseY, 15, 15);
            radioItem1.Bounds = radioBound1;
            page.Canvas.DrawString("Option 1", font, brush2, new PointF(baseX + 20, baseY));

            PdfRadioButtonListItem radioItem2 = new PdfRadioButtonListItem("option2");
            RectangleF radioBound2 = new RectangleF(baseX + 70, baseY, 15, 15);
            radioItem2.Bounds = radioBound2;
            page.Canvas.DrawString("Option 2", font, brush2, new PointF(baseX + 90, baseY));
            radioButtonListField.Items.Add(radioItem1);
            radioButtonListField.Items.Add(radioItem2);
            radioButtonListField.SelectedIndex = 0;
            doc.Form.Fields.Add(radioButtonListField);
            baseY += 25;

            //Add a combobox
            page.Canvas.DrawString("ComboBox:", font, brush1, new PointF(10, baseY));
            RectangleF cmbBounds = new RectangleF(baseX, baseY, 150, 15);
            PdfComboBoxField comboBoxField = new PdfComboBoxField(page, "combobox");
            comboBoxField.Bounds = cmbBounds;
            comboBoxField.Items.Add(new PdfListFieldItem("Item 1", "item1"));
            comboBoxField.Items.Add(new PdfListFieldItem("Item 2", "itme2"));
            comboBoxField.Items.Add(new PdfListFieldItem("Item 3", "item3"));
            comboBoxField.Items.Add(new PdfListFieldItem("Item 4", "item4"));
            comboBoxField.SelectedIndex = 0;
            comboBoxField.Font = font;
            doc.Form.Fields.Add(comboBoxField);
            baseY += 25;

            //Add a signature field
            page.Canvas.DrawString("Signature Field:", font, brush1, new PointF(10, baseY));
            PdfSignatureField sgnField = new PdfSignatureField(page, "sgnField");
            RectangleF sgnBounds = new RectangleF(baseX, baseY, 150, 80);
            sgnField.Bounds = sgnBounds;
            doc.Form.Fields.Add(sgnField);
            baseY += 90;

            //Add a button
            page.Canvas.DrawString("Button:", font, brush1, new PointF(10, baseY));
            RectangleF btnBounds = new RectangleF(baseX, baseY, 50, 15);
            PdfButtonField buttonField = new PdfButtonField(page, "button");
            buttonField.Bounds = btnBounds;
            buttonField.Text = "Submit";
            buttonField.Font = font;
            PdfSubmitAction submitAction = new PdfSubmitAction("https://www.e-iceblue.com/getformvalues.php");
            submitAction.DataFormat = SubmitDataFormat.Html;
            buttonField.Actions.MouseDown = submitAction;
            doc.Form.Fields.Add(buttonField);

            //Save to file
            doc.SaveToFile("FillableForms.pdf", FileFormat.PDF);
        }
    }
}

C#/VB.NET: Create, Fill, or Remove Fillable Forms in PDF

Fill Form Fields in an Existing PDF Document

In order to fill out a form, we must first get all the form fields from the PDF document, determine the type of a certain field, and then input a value or select a value from a predefined list. The following are the steps to fill form fields in an existing PDF document using Spire.PDF for .NET.

  • Create a PdfDocument object.
  • Load a sample PDF document using PdfDocument.LoadFromFile() method.
  • Get the form from the document through PdfDocument.Form property.
  • Get the form widget collection through PdfFormWidget.FieldsWidget property.
  • Loop through the form widget collection to get a specific PdfField.
  • Determine if the PdfField is a certain field type such as text box. If yes, set the text of the text box through PdfTextBoxFieldWidget.Text property.
  • Repeat the sixth step to fill radio button, check box, combo box, and list box with values.
  • Save the document to a PDF file using PdfDocument.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Pdf;
using Spire.Pdf.Fields;
using Spire.Pdf.Widget;

namespace FillFormFields
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a PdfDocument object
            PdfDocument doc = new PdfDocument();

            //Load a template containing forms
            doc.LoadFromFile(@"C:\Users\Administrator\Desktop\FormsTemplate.pdf");

            //Get the form from the document
            PdfFormWidget form = (PdfFormWidget)doc.Form;

            //Get the form widget collection
            PdfFormFieldWidgetCollection formWidgetCollection = form.FieldsWidget;

            //Loop through the widgets
            for (int i = 0; i < formWidgetCollection.Count; i++)
            {
                //Get a specific field
                PdfField field = formWidgetCollection[i];

                //Determine if the field is a text box
                if (field is PdfTextBoxFieldWidget)
                {
                    if (field.Name == "name")
                    {
                        //Set the text of text box
                        PdfTextBoxFieldWidget textBoxField = (PdfTextBoxFieldWidget)field;
                        textBoxField.Text = "Kaila Smith";
                    }
                }

                //Determine if the field is a radio button
                if (field is PdfRadioButtonListFieldWidget)
                {
                    if (field.Name == "gender")
                    {
                        //Set the selected index of radio button
                        PdfRadioButtonListFieldWidget radioButtonListField = (PdfRadioButtonListFieldWidget)field;
                        radioButtonListField.SelectedIndex = 1;
                    }
                }

                //Determine if the field is a combo box
                if (field is PdfComboBoxWidgetFieldWidget)
                {
                    if (field.Name == "country")
                    {
                        //Set the selected index of combo box
                        PdfComboBoxWidgetFieldWidget comboBoxField = (PdfComboBoxWidgetFieldWidget)field;
                        int[] index = { 0 };
                        comboBoxField.SelectedIndex = index;
                    }
                }

                //Determine if the field is a check box
                if (field is PdfCheckBoxWidgetFieldWidget)
                {
                    //Set the "Checked" status of check box
                    PdfCheckBoxWidgetFieldWidget checkBoxField = (PdfCheckBoxWidgetFieldWidget)field;
                    switch (checkBoxField.Name)
                    {
                        case "travel":
                            checkBoxField.Checked = true;
                            break;
                        case "movie":
                            checkBoxField.Checked = true;
                            break;
                    }
                }

                //Determine if the field is a list box
                if (field is PdfListBoxWidgetFieldWidget)
                {
                    if (field.Name == "degree")
                    {
                        //Set the selected index of list box
                        PdfListBoxWidgetFieldWidget listBox = (PdfListBoxWidgetFieldWidget)field;
                        int[] index = { 1 };
                        listBox.SelectedIndex = index;
                    }
                }
            }

            //Save to file
            doc.SaveToFile("FillFormFields.pdf", FileFormat.PDF);
        }
    }
}

C#/VB.NET: Create, Fill, or Remove Fillable Forms in PDF

Remove a Particular Field or All Fields from an Existing PDF Document

A form field in a PDF document can be accessed by its index or name and removed by PdfFieldCollection.Remove() method. The following are the steps to remove a particular field or all fields from an existing PDF document using Sprie.PDF for .NET.

  • Create a PdfDocument object.
  • Load a PDF document using PdfDocument.LoadFromFile() method.
  • Get the form widget collection from the document.
  • Loop through the widget collection to get a specific PdfField. Remove the field one by one using PdfFieldCollection.Remove() method.
  • To remove a certain form field, get it from the document through PdfFormWidget.FieldsWidget["fieldName"] property and then call the PdfFieldCollectiont.Remove() method.
  • Save the document to a PDF file using PdfDocument.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Pdf;
using Spire.Pdf.Fields;
using Spire.Pdf.Widget;

namespace RemoveFormFields
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a PdfDocument object
            PdfDocument doc = new PdfDocument();

            //Load a PDF file
            doc.LoadFromFile(@"C:\Users\Administrator\Desktop\FormsTemplate.pdf");

            //Get the form fields from the document
            PdfFormWidget formWidget = doc.Form as PdfFormWidget;

            //Loop through the widgets
            for (int i = formWidget.FieldsWidget.List.Count - 1; i >= 0; i--)
            {
                //Get a specific field
                PdfField field = formWidget.FieldsWidget.List[i] as PdfField;

                //Remove the field
                formWidget.FieldsWidget.Remove(field);
            }

            //Get a specific field by its name
            //PdfField field = formWidget.FieldsWidget["name"];
            //Remove the field
            //formWidget.FieldsWidget.Remove(field);

            //Save to file
            doc.SaveToFile("DeleteAllFields.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.

Published in Form Field
Page 2 of 2