Hướng dẫn php fill pdf form

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.

Today PDF files have become one of the most common methods of sharing documents online. Using a PDF document is often the foremost option whether you need to provide your clients’ documents to third-party service providers like insurance companies or banks, or simply need to send a CV to an employer. Working with PDF files allows you to share plain as well as formatted text, hyperlinks, images, and even different fillable forms that you need.

In this blog, we will be understanding that how one can fill out PDF forms using PHP and a tremendous PDF manipulation tool known as PDFtk Server. Here we will be demonstrating how one can work dynamically by adding data in PDF form through Html forms.

A fillable PDF is a PDF document that contains some fields that are editable without PDF editor software. To fill the fillable PDF dynamically one has to create an HTML form and dynamically bind it. To accomplish this, we will create a PHP script.

Below are the following step and some software & library to fill fillable PDF.

Prerequisites:

  • PDFtk Server – PDF manipulation software
  • Composer – Composer
  • php-pdftk Library for PDFtk

Step 1) Go to the above PDFtk server Link and install the PDFtk server according to your operating system.

Hướng dẫn php fill pdf form

After installing the software open the command prompt and run Command:

Hướng dẫn php fill pdf form

Step 2) Create a folder for the script on your local server, folder name can be anything. In this case, we have created a folder named: “fillable-pdf”, now create index.php in fillable-pdf folder.

www/public_html/ fillabe-pdf/index.php






How To Fill A Fillable PDF Form with PHP using PDFtk






Generate Fillable PDF Dynamically

Fill the form and your data will fill in a PDF

Create style.css file for form looks good. www/public_html/ fillabe-pdf/style.css

body {
padding: 5rem 0;
}

.btn-block {
display: block;
width: 10%;
}

.btn-success {
color: #fff;
background-color: #0062cc;
border-color: #007bff;
}

.btn-success:hover {
color: #fff;
background-color: #0062cc;
border-color: #0062cc;
}

Hướng dẫn php fill pdf form

Step 3) Create composer.json file for installing PDFtk library.

www/public_html/ fillabe-pdf/composer.json

{
"name": "mrdigital/pdftk",
"autoload" : {

"psr-4" : {

"Classes\\":"./classes"

}
},
"require": {
"mikehaertl/php-pdftk": "^0.10.3"
}
}

After this, run this command:

Composer require mikehaertl/php-pdftk, this command creates a vendor folder and downloads the PDFtk library.

Step 4) Check the sample fillable pdf file fields and map fields with handler.php file. Then open fillable pdf on any editor software to check input fields with mapped fields names. You can use this https://www.pdffiller.com/ site to get field’s name.

Hướng dẫn php fill pdf form

Also, read: Extract any type of data from excel sheet using Azure function

Step 5) Create a handler file to handle post requests, mapping pdf fields value to post form value.

www/public_html/ fillabe-pdf/handler.php

 $_POST['fname'] .' ' . $_POST['lname'],
'email_field' => $_POST['email'],
'phone_field' => $_POST['phone'],
'enquiry_field' => $_POST['message']
];

$pdf = new GeneratePdf;
$response = $pdf->generate($data);

print_r($response);

Step 6) Create Folder Classes for Create class GenratePDF.

www/public_html/ fillabe-pdf/classes/GeneratePDF.php

fillForm($data)
->flatten()
->saveAs( './pdf_fill/' . $filename);
return $filename;
}
catch(Exception $e)
{
return $e->getMessage();
}

}
}

Step 7) Create a pdf_fill folder for storing fillable pdf.

Step 8) Protect your folder for security reasons, create index.php empty file in classes and pdf_fill folder.

www/public_html/ fillabe-pdf/classes/index.php or www/public_html/ fillabe-pdf/pdf_fill/index.php

Also, read: Top Web app development frameworks for 2022: get the most scalability at lower costs

Wrapping Up

With the above implementation, you can install PDFtk and learn some of its useful commands like dump_data_fields and fill_form. With all the above steps you will be able to successfully achieve the pdf fillable custom functionality.

Please note that this implementation is basic, and we have tried to keep things as simple as possible. If still, you are having some problem you can connect with our development team for any further assistance.

Hướng dẫn php fill pdf form

Web Development Services

Are you looking for a reliable web development company? Our highly skilled web developers enables us to deliver result oriented web development services. Contact our team to understand, how we can help you in achieving your business goals.


Looking for more awesome content? Join Our Newsletter


RELATED BLOGS