31

I have many PDF forms, I would need to fill them each in php with the data I already have.

Here is just a sample PDF form , I want to fill this form using php. The data I already have in DB. I just want to fill this form and save it.

I am working in PHP Zend Framework.

All I want is when I would download those forms from my site, it would pre-fill all the fields in the pdf form with the information I already have.

Please help me.

4 Answers 4

43

Calling pdftk is a nice way to accomplish this. I'll assume that you know how to execute an external program and leave that out.

First, create an FDF file from your PDF.

pdftk form.pdf generate_fdf output data.fdf

You can now use that as template. The sample that you provided looks like this:

%FDF-1.2
%<E2><E3><CF><D3>
1 0 obj 
<<
/FDF 
<<
/Fields [
<<
/V ()
/T (Date)
>> 
<<
/V /
/T (CheckBox2)
>> 
<<
/V /
/T (CheckBox3)
>> 
<<
/V /
/T (CheckBox4)
>> 
<<
/V /
/T (CheckBox5)
>> 
<<
/V ()
/T (Your_Last_Name)
>> 
<<
/V ()
/T (Your_First_Name)
>> 
<<
/V /
/T (CheckBox1)
>>]
>>
>>
endobj 
trailer

<<
/Root 1 0 R
>>
%%EOF

The fields are lines that start with /V (). Enter your desired values into those fields. For example:

%FDF-1.2
%<E2><E3><CF><D3>
1 0 obj 
<<
/FDF 
<<
/Fields [
<<
/V (February 4, 2012)
/T (Date)
...

Finally, merge the FDF with the PDF. Execute the command:

pdftk form.pdf fill_form data.fdf output form_with_data.pdf

If you don't need to keep the FDF and generated PDF files, you can simply pipe the data via stdin and stdout instead of using temp files.

10
  • Thank you so much for your answer. I would need a little more from you, Is PDFTK something should be installed on server ?? I didn't work with PDF much, is there some example, or could you explain a bit more that how could I execute external program?? Please help me out.
    – Sohail
    Commented Feb 4, 2012 at 20:43
  • Yes, install pdftk on the server. You can find the instructions here. To execute system commands from PHP simply call the exec function. For example. <?php exec('/usr/bin/pdftk form.pdf fill_form data.fdf output form_with_data.pdf'); ?> Commented Feb 4, 2012 at 22:42
  • Thanx Richard, I will try. Thanks a million.
    – Sohail
    Commented Feb 5, 2012 at 8:18
  • @RichardAyotte This was a good find :) I have to do the exact same thing, with a twist. I need also to include an image in one of the form fields. How would I do that?
    – dorphalsig
    Commented Dec 2, 2013 at 3:44
  • 1
    To "tick" a checkbox in FDF format use /V /Yes Commented Jan 26, 2021 at 15:53
19

I found this and it works for me. It is an unofficial patch for Zend to fill FDF Form Fields.Site with the discussion and patch

NO INSTALLATION, NO OUTSIDE PROGRAMS, NO COORDINATES

Use:

$pdf = Zend_Pdf::load('input-file-containing-form.pdf');
$pdf->setTextField('name', 'Someone');
$pdf->setTextField('address', '1 Main Street');
$pdf->setTextField('city', 'Cyberspace');
$pdf->save('outputfile.pdf');

If page no longer exists here is the patch for PDF.php (if someone have problems - write me privete message):

--- Pdf.php.orig    2009-11-15 17:52:57.000000000 +0100
+++ Pdf.php 2010-01-07 04:05:23.000000000 +0100
@@ -202,6 +202,13 @@
      * @var array
      */
     protected static $_inheritableAttributes = array('Resources', 'MediaBox', 'CropBox', 'Rotate');
+    
+    /**
+     * List of form fields
+     *
+     * @var array - Associative array, key: name of form field, value: Zend_Pdf_Element
+     */
+    protected $_formFields = array();

     /**
      * Request used memory manager
@@ -315,6 +322,7 @@

             $this->_loadNamedDestinations($this->_trailer->Root, $this->_parser->getPDFVersion());
             $this->_loadOutlines($this->_trailer->Root);
+            $this->_loadFormfields($this->_trailer->Root);

             if ($this->_trailer->Info !== null) {
                 $this->properties = $this->_trailer->Info->toPhp();
@@ -557,6 +565,61 @@
             $this->_originalOpenOutlinesCount = $root->Outlines->Count->value;
         }
     }
+    
+    /**
+     * Load form fields
+     * Populates the _formFields array, for later lookup of fields by name
+     *
+     * @param Zend_Pdf_Element_Reference $root Document catalog entry
+     */
+    protected function _loadFormFields(Zend_Pdf_Element_Reference $root)
+    {
+      if ($root->AcroForm === null || $root->AcroForm->Fields === null) {
+        return;
+      }
+      
+      foreach ($root->AcroForm->Fields->items as $field)
+      {
+          if ( $field->FT->value == 'Tx' && $field->T !== null ) /* We only support fields that are textfields and have a name */
+          {
+              $this->_formFields[$field->T->value] = $field;
+          }
+      }
+      
+      if ( !$root->AcroForm->NeedAppearances || !$root->AcroForm->NeedAppearances->value )
+      {
+        /* Ask the .pdf viewer to generate its own appearance data, so we do not have to */
+        $root->AcroForm->add(new Zend_Pdf_Element_Name('NeedAppearances'), new Zend_Pdf_Element_Boolean(true) );
+        $root->AcroForm->touch();
+      }
+    }
+    
+    /**
+     * Retrieves a list with the names of the AcroForm textfields in the PDF
+     *
+     * @return array of strings
+     */
+    public function getTextFieldNames()
+    {
+      return array_keys($this->_formFields);
+    }
+    
+    /**
+     * Sets the value of an AcroForm text field
+     *
+     * @param string $name Name of textfield
+     * @param string $value Value
+     * @throws Zend_Pdf_Exception if the textfield does not exist in the pdf
+     */
+    public function setTextField($name, $value)
+    {
+      if ( !isset($this->_formFields[$name]))
+        throw new Zend_Pdf_Exception("Field '$name' does not exist or is not a textfield");
+      
+      $field = $this->_formFields[$name];
+      $field->add(new Zend_Pdf_Element_Name('V'), new Zend_Pdf_Element_String($value) );
+      $field->touch();      
+    }

     /**
      * Orginize pages to tha pages tree structure.
4
  • 4
    Thanks, this is much better than installing extra software. I can't quite believe that this patch NEVER made it into Zend Framework though.
    – Steve Hill
    Commented Dec 6, 2012 at 10:35
  • I've just downloaded the Zend Framework and the patch is already in there... So no need to patch now. Commented Oct 29, 2015 at 14:07
  • 1
    @GonzaloBrusco Was it in the full package or just the Zend PDF library from github? I was hoping to use just zend pdf for a project but it looks like there are so many zend dependencies, it's almost useless on its own. Definitely none of this code in there at all from what I can see.
    – Jestep
    Commented Dec 22, 2015 at 21:34
  • 6
    @Jestep - I just found it here: github.com/zf1/zend-pdf and it's happily working out of the box, with the patch already in the code. Very easy to install just it and the 4 required Zend dependencies using Composer - run composer require zf1/zend-pdf and add require_once '<path to Composer's vendor dir>/autoload.php'; to the file where you need to use the PDF functionality. Commented May 8, 2017 at 17:24
15

I found fpdf library looking for the same on internet.

http://www.fpdf.org/en/script/script93.php

Code looks clean, easy to use and remember it, and works for pdf with forms (fillable).

<?php

/***************************
  Sample using a PHP array
****************************/

require('fpdm.php');

$fields = array(
    'name'    => 'My name',
    'address' => 'My address',
    'city'    => 'My city',
    'phone'   => 'My phone number'
);

$pdf = new FPDM('template.pdf');
$pdf->Load($fields, false); // second parameter: false if field values are in ISO-8859-1, true if UTF-8
$pdf->Merge();
$pdf->Output();
?>

It comes with example that worked out of the box. Hope it helps.

7
  • 1
    I even used it to just JOIN pdf's pages using from_template function and being able to print 150 pages of documents intead 150 files of 1 page. Some systems doesn't let you select 150 files then print them. The last time i saw that in ie: Windows i noticed that i was only capable to pick up to 15 ... weird. I was using a macro recorder to print them all, but finally joining them with fpdf was much more efficient, clean and less prone to errors. Regards.
    – m3nda
    Commented Jun 8, 2018 at 16:27
  • It does not support xfa/xdp, which is the form format currently used by Adobe.
    – Tobi G.
    Commented Jun 12, 2018 at 11:51
  • Project seems dead, however, should be OK if there's no PDF min version requeriment on the project: Create the form in a supported version with your form-creating tool and it should be okey. I'm gona try it.
    – DGoiko
    Commented Feb 18, 2019 at 17:37
  • 3
    Confirm this works. As explained in the website, if your PDF is a newer version, just do a pdftk modele.pdf output modele2.pdf and it will work.
    – Ivan
    Commented Mar 13, 2020 at 19:02
  • 6
    Someone took the project and now is being updated here: github.com/codeshell/fpdm
    – cesAR
    Commented Jun 24, 2020 at 19:59
2

The Zend_Pdf-component can draw text in your pdf, but it is a bit clumsy as you have to specify the x- and y-coordinates on your pdf-page. Something like that:

// This is the pdf-file you want to fill out...
$pdf = Zend_Pdf::load('/path/to/pdf-template.pdf')
$page = $pdf->pages[0]; // Use first page
$page->drawText("firstname lastname", 200, 600);
...
$pdf->pages[0] = $page;
// be sure to write to a new file, not the original empty  form.
$pdf->save('/path/to/pdf-output.pdf');

I don't know if there are easy ways to find the exact coords, I usually play around until it fits.

2
  • But this is not filling the PDF form, this would diffidently work for flat PDFs but now for fallible PDF forms.
    – Sohail
    Commented Feb 4, 2012 at 20:44
  • I know, should have mentioned that. But as far as I know, this is the only way you can put text into a pdf using Zend_Pdf.
    – dbrumann
    Commented Feb 5, 2012 at 12:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.