Remove/Delete Form Fields from PDF in C#

2017-08-21 07:54:45 Written by  support iceblue
Rate this item
(0 votes)

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.

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/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.

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

    }
}

Remove/Delete Form Fields from PDF in C#

Additional Info

  • tutorial_title:
Last modified on Sunday, 26 September 2021 02:12