Tutorial: Fill in PDF Fields With Submitted Form Data

Due to recent popularity of my original article (and a couple donations!), I was able to find some extra time to write out a tutorial on how to implement my original createFDF function into your website using both PDF as well as HTML forms to populate your PDF documents with submitted data. In order to follow this tutorial in whole, you will need to have the Adobe Acrobat software (not the reader, but the full application) and a web server that supports PHP. So without further delay, let's get down and dirty.

Back to article

Submitting Data to a PDF from via HTML and/or PDF forms

This is a short tutorial about how to implement my original createFDF function into your website OR web application so you can import user-submitted data into your PDF files. The most popular reason for using a method like this is so the data can be represented in a standard format that is easy to comprehend. This method can be useful for things like employment applications where you not only accept them online, but also through the mail. A single PDF document allows your web users to provide you with information in a variety of ways, but all are formatted to the way yout Human Resources department will expect to see them.

  1. Create your PDF document that you want the submitted data imported to.

    To do this, I had used Quark to create the initial document, but you can use pretty much any application to produce it. Since I am using Microsoft Windows, I just printed my document to the "Adobe PDF" entry in my printer control panel that was created when installing Acrobat. Initial PDF document (5.7 KB).

    Once you have your initial PDF document ready, it is time to add fields to import the data into.

    1. Open your PDF document, and select the Text Field Tool.

      Text Field Tool Button Location in Acrobat

      You can also access the Text Field Tool via the Tools » Advanced Editing » Forms menu.

    2. Draw your first text field. When you do, a window will pop up prompting for field information. There are quite a few options for each of the fields, but the only one we are concerned with for this tutorial is the "Name" property under the Genera; tab.

      Enter a name for this field name. Keep in mind that when submitted, PHP will automatically convert spaces to underscores when data is posted. Therefore, it's best not to use spaces in the first place (to save time later).

      Text Field option screen in Acrobat

      Repeat this step for the rest of your text fields. Notice that the Comments field would be a great place to use an HTML textarea field element. Therefore, in Acrobat's field properties, under the options tab, I have selected the "Multi-line" option.

      Multi-line text field option in Acrobat

    3. Save your PDF form. Notice that when you open it up again, it looks the same as the initial document. The only difference is that you can now place the cursor over the fields and actually type in information. PDF document with form (8.2 KB).

  2. Create the form that the users will fill in to submit the data.

    1. Using an HTML form to allow users to fill in the data.

      Create your HTML form for your web visitors to fill out. You do not have to include all the fields that your PDF uses. For instance, in this tutorial, I will automatically fill in the date field when the form is processed. Below is an example HTML form to use with this tutorial.

      <form method="post" action="submit_form.php">
       <fieldset>
        <table>
         <tr><td>Enter Your Name</td><td><input type="text" name="Text2" /></td></tr>
         <tr><td>Favorite Color</td><td><input type="text" name="Text3" /></td></tr>
         <tr><td>Age</td><td><input type="text" name="Text4" /></td></tr>
        </table>
        <p>
         <b>Comments:</b> abc<br />
         <textarea name="Text5" rows="5" cols="35"></textarea>
        </p>
        <input type="submit" value="Generate FDF Data" />
       </fieldset>
      </form>

      Here is how that would look in your borwser:

      Enter Your Name
      Favorite Color
      Age

      Comments: abc

    2. Using a PDF form to allow users to fill in the data.

      When using multi-page or long forms (a job application form for example), you may want to allow your visitors to simply fill in the PDF file to preserve formatting. You have 3 options:

      1. Have the users print the PDF and fill it in by hand and mail it,

      2. Have the users type in the information using the PDF, print it and mail it or

      3. Have the users type in the information using the PDF and submit it online.

      Because of the nature of PDF documents, you can be fairly certain that any of these options will produce similar results. We can cover all three options without additional effort (assuming you want to be able to accept the submission online in the first place).

      Create the PDF that your visitors will fill out. In most cases, this will be the exact PDF that you created earlier with an added submit button, so let's add that.

      1. Open your PDF document that has the form and select the button tool.

      2. Draw the button in the document. This is what the users will click to submit the form.

      3. Select the Actions tab of the field properties.

      4. Select the Submit a Form option under the Select Action field and click the Add button.

        • Select the HTML Export Format.

        • Enter the URL of the processing script.

        • Select All fields option for the Field Selection

        • Select All fields option for the Field Selection

        • Click OK

        Multi-line text field option in Acrobat

      5. Save your visitor PDF file. PDF document with user form (9.0 KB).

  3. Add your data-processing PHP script to handle the posted data.

    The very first thing you will want to do is check that you are getting the data you expect when a form is submitted. The best way to do this is to create your processing script with the only following code:

    <?php echo '<pre>'; print_r($_POST); echo '</pre>'; ?>

    This will show you how your submitted data is coming across, field names and all. Check the field names against the names used in your PDF file that the data will be imported to. An example output may look like this:

    Array
        (
            [Text2] => Justin Kovisto
            [Text3] => Purple
            [Text4] => 28
            [Text5] => This tutorial is taking more time than I thought! ;)
            [Button6] => Submit Online
        )

    Once you have verified that the field names are the same as in your PDF file, you can start writing your processing script. For this example, we will simply take the submitted information and write an fdf file to the server's filesystem to use later. (I also have created versions of this processing script to store the FDF data in a database for later retrieval as well as emailing the file as an attachment.)

    Firstly, you only want to attempt to process if a form was posted and the information you wanted was there. Add your custom verification routines and errors as you see fit. I will keep this very simple (and probably not that secure) for illustration purposes. Here is an example processing script:

    
    <?php
    
        
    // check that a form was submitted
        
    if(isset($_POST) && is_array($_POST) && count($_POST)){
            
    // we will use this array to pass to the createFDF function
            
    $data=array();
            
            
    // This displays all the data that was submitted. You can
            // remove this without effecting how the FDF data is generated.
            
    echo'<pre>POST 'print_r($_POST);echo '</pre>';

            if(isset(
    $_POST['Text2'])){
                
    // the name field was submitted
                
    $pat='`[^a-z0-9\s]+$`i';
                if(empty(
    $_POST['Text2']) || preg_match($pat,$_POST['Text2'])){
                    
    // no value was submitted or something other than a
                    // number, letter or space was included
                    
    die('Invalid input for Text2 field.');
                }else{
                    
    // if this passed our tests, this is safe
                    
    $data['Text2']=$_POST['Text2'];
                }
                
                if(!isset(
    $_POST['Text3'])){
                    
    // Why this? What if someone is spoofing form submissions
                    // to see how your script works? Only allow the script to
                    // continue with expected data, don't be lazy and insecure ;)
                    
    die('You did not submit the correct form.');
                }
                
                
    // Check your data for ALL FIELDS that you expect, ignore ones you
                // don't care about. This is just an example to illustrate, so I
                // won't check anymore, but I will add them blindly (you don't want
                // to do this in a production environment).
                
    $data['Text3']=$_POST['Text3'];
                
    $data['Text4']=$_POST['Text4'];
                
    $data['Text5']=$_POST['Text5'];
                
                
    // I wanted to add the date to the submissions
                
    $data['Text1']=date('Y-m-d H:i:s');
                
                
    // if we got here, the data should be valid,
                // time to create our FDF file contents
                
                // need the function definition
                
    require_once 'createFDF.php';
                
                
    // some variables to use
                
                // file name will be <the current timestamp>.fdf
                
    $fdf_file=time().'.fdf';
                
                
    // the directory to write the result in
                
    $fdf_dir='';
                
                
    // need to know what file the data will go into
                
    $pdf_doc='Project2.pdf';
                
                
    // generate the file content
                
    $fdf_data=createFDF($pdf_doc,$data);

                
    // this is where you'd do any custom handling of the data
                // if you wanted to put it in a database, email the
                // FDF data, push ti back to the user with a header() call, etc.

                // write the file out
                
    if($fp=fopen($fdf_file,'w')){
                    
    fwrite($fp,$fdf_data,strlen($fdf_data));
                    echo 
    $fdf_file,' written successfully.';
                }else{
                    die(
    'Unable to create thr file: '.$fdf_dir.'/'.$fdf_file);
                }
                
    fclose($fp);
            }
        }else{
            echo 
    'You did not submit a form.';
        }
    ?>

    You will also need the createFDF.php file in the same directory. This file has the following contents:

    
    <?php
    
    /*
    KOIVI HTML Form to FDF Parser for PHP (C) 2004 Justin Koivisto
    Version 2.1.2
    Last Modified: 9/12/2005

        This library is free software; you can redistribute it and/or modify it
        under the terms of the GNU Lesser General Public License as published by
        the Free Software Foundation; either version 2.1 of the License, or (at
        your option) any later version.

        This library is distributed in the hope that it will be useful, but
        WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
        or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
        License for more details.

        You should have received a copy of the GNU Lesser General Public License
        along with this library; if not, write to the Free Software Foundation,
        Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 

        Full license agreement notice can be found in the LICENSE file contained
        within this distribution package.

        Justin Koivisto
        justin.koivisto@gmail.com
        https://koivi.com
    */

    /*
    *   createFDF
    *
    *   Takes values submitted via an HTML form and fills in the corresponding
    *   fields into an FDF file for use with a PDF file with form fields.
    *
    *   @param  $file   The pdf file that this form is meant for. Can be either
    *                   a url or a file path.
    *   @param  $info   The submitted values in key/value pairs. (eg. $_POST)
    *   @result Returns the FDF file contents for further processing.
    */
    function createFDF($file,$info){
        
    $data="%FDF-1.2\n%âãÏÓ\n1 0 obj\n<< \n/FDF << /Fields [ ";
        foreach(
    $info as $field => $val){
            if(
    is_array($val)){
                
    $data.='<</T('.$field.')/V[';
                foreach(
    $val as $opt)
                    
    $data.='('.trim($opt).')';
                
    $data.=']>>';
            }else{
                
    $data.='<</T('.$field.')/V('.trim($val).')>>';
            }
        }
        
    $data.="] \n/F (".$file.") /ID [ <".md5(time()).">\n] >>".
            
    " \n>> \nendobj\ntrailer\n".
            
    "<<\n/Root 1 0 R \n\n>>\n%%EOF\n";
        return 
    $data;
    }
    ?>

Code Download

This tutorial is now included in the source code that is available for download as part of the first article.


Warning: include_once(site_menu.php): failed to open stream: No such file or directory in D:\data\htdocs\www.mofirst.org\witness\pdf\tutorial.php on line 234

Warning: include_once(): Failed opening 'site_menu.php' for inclusion (include_path='.;C:\xampp\php\PEAR') in D:\data\htdocs\www.mofirst.org\witness\pdf\tutorial.php on line 234