Skip to main content Skip to footer

Build a JavaScript App with Interactive PDF Forms

When would you need to create a JavaScript application with interactive form fields? Consider this scenario: you attend a conference with multiple sessions and different speakers. At the end of each session, you are given a feedback form that should be filled out and handed over to the event personnel.

How many people would be interested in submitting the feedback? If the same form is shared via an online link, it would be more convenient to submit feedback. The form could be as simple as a button click on your mobile device. Designing such platforms is a common scenario; we now gather information online in a predefined format using these forms.

This article will help you build a JavaScript-based PDF application which allows you to load an interactive form into the viewer. This viewer supports filling out a form. After the form has been completed, users can click the submit button and save the finished form in PDF format on the server.

We are using Grapecity Documents for PDF and the Documents PDF Viewer to view/fill the interactive PDF forms and the Grapecity Documents for Pdf API to collect the form data and save it as a PDF file on the server.

We'll use an Event Feedback form to gather the feedback from the conference audience. The form includes a feedback questionnaire in the form of multiple choice questions. The multiple choices have been provided by using the RadioButton form field. You can try using a different form created using the other types of form fields.

Step 1: Load blank PDF form in GcDocs Pdf Viewer

GcDocs Pdf Viewer is a client-side JavaScript-based control that enables you to load, view, edit, and save the PDF files on the browser. The extensive client-side API of this control provides methods and properties to perform these functions.

The open method of GcDocs Pdf Viewer is used to load PDF documents into the viewer and hence enables the users to view and process the PDF document. The viewer supports many standard PDF features while loading the PDF file as listed here.

The code below uses the open method to load the interactive PDF form in the GcDocs Pdf Viewer.

<script>

    function loadPdfViewer(selector) {

        var viewer = new GcPdfViewer(selector, { renderInteractiveForms: true });           

        viewer.addDefaultPanels();           

        viewer.open("StaticFiles/FormSubmit.pdf");

    }

</script>
This is how the blank form loaded in the viewer looks:

How to create interactive PDFs on the web

Step 2: Fill and submit the form

The interactive PDF form loaded in the GcDocs Pdf Viewer is completely editable and can be filled-in by the user. Perform the required action, like clicking in the text fields, radio buttons, checkboxes or opening the dropdown for ComboBox, and more. The document can be processed in many more ways using the viewer features as listed here.

The Event Feedback form loaded in the viewer consists of the Text fields and Radio buttons. Here you enter or select the appropriate values in the form and click on the submit button to save the filled-in form on the server.

The filled-in form on the browser looks like this:

Build an App with Interactive PDF Forms

Step 3: Save the filled PDF form on the server

Once the form has been filled in and the user has clicked the Submit button, the data entered in the form is sent to the server-side. A copy of the PDF form will be saved on the server.

This is where the GcPdf API comes into action. This API lets you process the PDF documents in multiple ways by providing a rich collection of API members, see details here.

Using this GcPdf API, a handler method has been defined on the server-side that parses the client response and builds the 'values' collection by filling it with the submitted field values. This method is invoked when the user clicks on the Submit button.

Here is the sample code snippet for the handler method:

public IActionResult Index(IFormCollection fields)  
{  
    //Parses the client response and builds the 'values' collection  
   //filling it with the submitted field values.  
   var fieldsTree = new List<FieldExportEntry>();  
   foreach (var key in fields.Keys)  
   {  
      if (fields.TryGetValue(key, out StringValues value))  
      {  
         var node = new FieldExportEntry() { Name = key };  
         if (TryParseRadioButtonsSet(value, out int selectedIndex))  
         {  
             node.Values = new List<string>() { selectedIndex.ToString(System.Globalization.CultureInfo.InvariantCulture) };  
         }  
        else  
        {  
            foreach (var v in value)  
            { 

                if (node.Values == null) node.Values = new List<string>(); node.Values.Add(v);

            }  
        }  
        fieldsTree.Add(node);  
      }  
   }

   ImportFormData(fieldsTree);

   return View();  
 }

The above defined handler method performs the following actions on the ‘values’ collection created in the Handler method, to save the PDF file on the server:

  1. Invokes a method to prepare the XML using the values collection created in the above step.

  public static void SaveFieldsToXML(List<FieldExportEntry> values, Stream stream)

          {  
              XmlWriterSettings xws = new XmlWriterSettings()  
              {  
                  Indent = true,  
                  CloseOutput = false,  
                  Encoding = Encoding.UTF8  
             };  
            using (XmlWriter xw = XmlWriter.Create(stream, xws))  
            {  
               xw.WriteStartElement("fields");  
               xw.WriteAttributeString("xmlns", "xfdf", null, "[http://ns.adobe.com/xfdf-transition/](http://ns.adobe.com/xfdf-transition/)");  
               foreach (var ftn in values)  
               {  
                  xw.WriteStartElement(ftn.Name);  
                  foreach (var v in ftn.Values)  
                  {  
                       xw.WriteStartElement("value");  
                       xw.WriteString(v == "true" ? "Yes" : v);  
                       xw.WriteEndElement();  
                  }  
                  xw.WriteEndElement();  
               }  
              xw.WriteEndElement();  
            }  
          }
  1. Imports the XML data into a newly created PDF document and save the resulting PDF on the server side.

    The ImportFormDataFromXML from GcPdf API is used to import the xml data and the Save method from GcPdfAPI is used to save the PDF file on the server.

public static void ImportFormData(List<FieldExportEntry> values)

        {
              GcPdfDocument pdf = new GcPdfDocument();
              using (var fs = new FileStream(Path.Combine("MyNewStaticFiles", "EventFeedbackForm_Filled.pdf"), FileMode.Open, FileAccess.Read))
              {
                  pdf.Load(fs);
                  using (var ms = new FileStream("FormFields_Filled.xml", FileMode.Create))
                  {
                      SaveFieldsToXML(values, ms);
                      ms.Seek(0, SeekOrigin.Begin);
                      pdf.ImportFormDataFromXML(ms);
                  }

              //Save the filled-in form on the server
              pdf.Save("filledForm.pdf");
          }
       }


Here is a quick view of the filled-in form saved on the server:

Interactive PDF form

Now that you have your interactive PDF form, you can easily add one to your next application. With a powerful document API, you can collect form data and save it as a PDF file on the server. The viewer allows you to visualize and process the PDF document. Once you mast the process with these quick and efficient tools, it will be less cumbersome for end-users to provide the information you’re looking for. If you need to create and application that includes an interactive form (or more than one), you know the steps to make the submission process as seamless as possible.

Try using the GcDocs Pdf Viewer to load the PDF files and explore the different PDF features supported by the viewer including forms, annotations, JavaScript actions, password protected documents, and more.

Manpreet Kaur - Senior Software Engineer

Manpreet Kaur

Senior Software Engineer
comments powered by Disqus