SelectPdf for .NET - Pdf Form Fields Filling - C# / ASP.NET MVC Sample

This sample shows how to use SelectPdf Library for .NET to load an existing document that contains an AcroForm PDF form, fill some of the fields and save the document.

Here is our test pdf document that contains a PDF form:
Test form

Click on the "Create PDF" button below to see the result.


Sample Code C#



using System.Web.Mvc;

namespace SelectPdf.Samples.Controllers
{
    public class PdfFormFillingController : Controller
    {
        // GET: PdfFormFilling
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult SubmitAction(FormCollection collection)
        {
            // the initial file
            string file = Server.MapPath("~/files/w-9.pdf");

            // load the pdf form manager
            PdfFormManager form = new PdfFormManager();
            form.Load(file);

            // fill some fields
            PdfFormFieldTextBox name =
                form.Fields["f1_1"] as PdfFormFieldTextBox;
            name.Text = "This is my name";

            PdfFormFieldTextBox businessName =
                form.Fields["f1_2"] as PdfFormFieldTextBox;
            businessName.Text = "This is my business name";

            PdfFormFieldCheckBox clasifIndividual =
                form.Fields["c1_1"] as PdfFormFieldCheckBox;
            clasifIndividual.Checked = true;

            PdfFormFieldTextBox address =
                form.Fields["f1_7"] as PdfFormFieldTextBox;
            address.Text = "This is my address";

            PdfFormFieldTextBox city =
                form.Fields["f1_8"] as PdfFormFieldTextBox;
            city.Text = "This is my city";

            PdfFormFieldTextBox employer1 =
                form.Fields["f1_14"] as PdfFormFieldTextBox;
            employer1.Text = "XX";

            PdfFormFieldTextBox employer2 =
                form.Fields["f1_15"] as PdfFormFieldTextBox;
            employer2.Text = "1234567";

            PdfFormFieldTextBox ssn1 =
                form.Fields["f1_11"] as PdfFormFieldTextBox;
            ssn1.Text = "123";

            PdfFormFieldTextBox ssn2 =
                form.Fields["f1_12"] as PdfFormFieldTextBox;
            ssn2.Text = "45";

            PdfFormFieldTextBox ssn3 =
                form.Fields["f1_13"] as PdfFormFieldTextBox;
            ssn3.Text = "6789";

            // save pdf document
            byte[] pdf = form.Save();

            // close pdf document
            form.Close();
           
            // return resulted pdf document
            FileResult fileResult = new FileContentResult(pdf, "application/pdf");
            fileResult.FileDownloadName = "Document.pdf";
            return fileResult;
        }
    }
}