How to programmatically fill out PDF forms using iText7 in c#

By Pranav Mittal | Views: 67

iText7 is a PDF library that allows you to work with pdf files. With the help of iText7 user can generate pdf files, manipulate data in existing pdf files and also able to manage the digital signature and more. iText7 is available under open source (AGPL) as well as a commercial license.

Features provided by iText7:

Generate PDFs:

Edit and manipulate PDFs:

  • Split or merge PDFs, delete pages from PDFs.
  • Rotate the entire PDF or specific pages.
  • Add and remove password protection from the PDF.
  • Update or add the content in existing PDF.
  • Programmatically fill out PDF forms (AcroForm and XFA)
  • Flatten AcroForms
  • Read XFA
  • Flatten XFA (with the pdfXFA iText add-on)
  • Adding digital signature.

To use iText7 in C#, we first need to install the iText NuGet from the NuGet package manager. To install the iText7 we can use the below command in visual studio Package Manager Console.

Once the NuGet is installed, we need to import the below Namespace in order to work with iText7.

using iText.Forms;
using iText.Forms.Fields;
using iText.Kernel.Pdf;

After that we need to create the object of PdfDocument class and provide two parameters, first is source file stream (template file which contain the form that we need to fill) and second is output file stream (once after filling the form where we need to save the filled file stream).

PdfDocument pdf = new PdfDocument(new PdfReader(sourceFileStream), new PdfWriter(outputStream));

To get the form from the pdf file we need to use the GetAcroForm function of PdfAcroForm class and pass the PdfDocument object and false (if form is not present and you want to create a form then pass true and if you don’t want to create a form then pass false) as parameter.

PdfAcroForm form = PdfAcroForm.GetAcroForm(pdf, false);

After that use GetFormFields function of PdfAcroForm class, this function returns the list of fields present in the pdf form.

IDictionary<String, PdfFormField> fields = form.GetFormFields();

Then we can use the fields id (e.g "Name" is the field id in the template pdf file) to set the fields value by using SetValue function of PdfFormField class like below:

PdfFormField toSet;
fields.TryGetValue("Name", out toSet);
toSet.SetValue("James Bond");

once the form is completely filled, close the pdf document using the close function present in PdfDocument class. And, after that convert the output memorystream in byte array and return to the user to download.

pdf.Close();
byte[] bytes = outputStream.ToArray();
return File(bytes, System.Net.Mime.MediaTypeNames.Application.Octet, "Editable.pdf");

Below you can see the complete implementation:

using iText.Forms;
using iText.Forms.Fields;
using iText.Kernel.Pdf;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using System.Web.Mvc;

namespace HackHackathon.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult DownloadPDF()
        {
            string path = @"\\Files\sample_pdf.pdf";
            path = Server.MapPath("~" + path);
            
            if (System.IO.File.Exists(path))
            {
                FileStream sourceFileStream = System.IO.File.OpenRead(path);
                MemoryStream outputStream = new MemoryStream();
                PdfDocument pdf = new PdfDocument(new PdfReader(sourceFileStream), new PdfWriter(outputStream));
                PdfAcroForm form = PdfAcroForm.GetAcroForm(pdf, true);
                if(form != null)
                {
                    IDictionary<String, PdfFormField> fields = form.GetFormFields();
                    PdfFormField toSet;

                    fields.TryGetValue("Name", out toSet);
                    toSet.SetValue("James Bond");

                    fields.TryGetValue("Language", out toSet);
                    toSet.SetValue("English");

                    pdf.Close();
                    byte[] bytes = outputStream.ToArray();
                    return File(bytes, System.Net.Mime.MediaTypeNames.Application.Octet, "Editable.pdf");
                }
            }
            return View("index",(object)"Source file does not exists!!");
        }
    }
}



Thank you for your feedback!