PDF forms with PDFtk & PHP. As we know that PDF files comes to be one of the most common options for people to share various documents online, whether the question comes about passing our client’s material to a third-party service providers such as banks, insurance companies and many other such firms or whether we send a CV to any employer with the help of PDF document, is frequently considered as the first option to work with. Well, working with PDF files lets you transfer plain as well as formatted text, images, hyperlinks, and even various forms that you need to be filled out.
Once your virtual machine is ready, and you have efficiently managed to login by ssh into your system, we can easily proceed with installing PDFtk by using apt-get:
1 |
sudo apt-get install pdftk |
To check if it works, we can run the following command:
The output should be similar to:
1 |
Copyright (c) 2003-16 Steward and Lee, LLC - Please Visit:www.pdftk.com. This is free software; see the source code for copying conditions. There is NO warranty, not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
Workflow
1) PDFtk comes with a broad range of manipulating features to work with PDF documents, by merging and splitting several pages to fill efficiently out your PDF forms.
2) This tool lets you apply watermarks. PDFtk viably makes utilization of FDF documents to control PDF shapes rapidly. FDF is regularly alluded to as the Form Data.
3) File that comprises of a plain-text file to help store data that is included in the form.
4) Next, you can quickly generate a FDF file from user submitted data and merge them with your original PDF files with the help of using PDFtk’s commands.
What includes inside the FDF file?
Header section
// Mention about PDF
2 |
1 0 obj<</FDF<< /Fields[ |
Content section
// Define all elments that you want to show in PDF
1 |
<< /T (employee_name) /V (Shikha) |
2 |
<< /T (designation) /V (Content Writer) |
Footer section
// Mention end process of PDF
Next your element’s value is prefixed with /V that signifies a value shown below:
1 |
<< /T(FIELD_NAME)/V(FIELD_VALUE) >> |
Alternatively, we can prefer to use PDFtk’s dump_data_fields command to extract easily numerous of field information from your file. Let’s see the code below:
1 |
pdftk path/to/the/form.pdf dump_data_fields > field_names.txt |
PDFtk will save the outcome in the field_names.txt record. Allude to beneath case:
03 |
FieldName: employee_name |
05 |
FieldJustification: Left |
08 |
FieldName: designation |
10 |
FieldJustification: Left |
PDFtk and PHP
PHP’s execss() function transforms a PDFtk format into PHP form. Let’s say for example: we hold a straightforward PDF structure with four content boxes by including a gathering of two radio catches. Let’s have a look below:
04 |
$desg = 'Content Writer; |
22 |
$fdf_content = "<</T(employee_name)/V({$ename})>>" ; |
23 |
$fdf_content .= "<</T(designation)/V({$desg})>>" ; |
25 |
$content = $fdf_header . $fdf_content , $fdf_footer ; |
27 |
$FDFfile = tempnam(sys_get_temp_dir(), gethostname()); |
28 |
file_put_contents ( $FDFfile , $content ); |
30 |
exec ( "pdftk form.pdf fill_form $FDFfile output.pdf" ); |
Next we will break the script in parts.
Define values to be written in the form.
Fetch all the values from the database table.
Outline a FDF record. Make a document by creating PHP’s tempnam capacity to store the FDF content.
Then access your PDFtk’s fill_form command with the help of PHP’s exec functionality. fill_form will merge your FDF file with raw PDF form.
Save the PHP file in your web root directory as pdftk.php name.
Working with Output File
It will further prevent future modifications by passing flatten message as a parameter to the fill_form command.
2 |
exec ( "pdftk select_exist_location/form.pdf fill_form $FDFfile output select_target_location/output.pdf flatten" ); |
Download your Output File
Instead of storing them on the disk, it’s better to download your output file:
03 |
exec ( "pdftk select_exist_location/form.pdf fill_form $FDFfile output output.pdf flatten" ); |
05 |
header( 'Content-Description: Move Files' ); |
06 |
header( 'Content-Type: application/octet-stream' ); |
07 |
header( 'Content-Disposition: attachment; filename=' . 'select_target_location/output.pdf' ); |
10 |
header( 'Cache-Control: must-revalidate' ); |
11 |
header( 'Pragma: public' ); |
13 |
header( 'Content-Length: ' . filesize ( 'output.pdf' )); |
15 |
readfile( 'output.pdf' ); |
By running the above script in the browser, you can easily download the output file to our machine.
Create a Wrapper class
04 |
'employee_name' => 'Shikha' , |
05 |
'designation' => 'Content writer' , |
07 |
$pdf = new PdfConfig( 'form.pdf' , $data ); |
09 |
->save( 'select_tartget_location/form-filled.pdf' ) |
We’ll make another record in the web root index and name it PdfConfig.php. Let’s name the class PdfConfig as well.
Class properties
The constructor
3 |
public function __construct( $pdfurl , $data ) { |
4 |
$this ->pdfurl = $pdfurl ; |
The constructor will appoint the PDF path and the structure information into their properties.
How to handle various temporary files
We know that PDFtk utilizes physical records to go well with its execution process. So, there is a need to generate temporary files during this process. Below here, we will write a method to develop various temporary files:
3 |
private function tmpfile() { |
4 |
return tempnam(sys_get_temp_dir(), gethostname()); |
Extract the form section
So, now let’s write the code to extract the form:
3 |
public function fields( $pretty = false) { |
4 |
$tmp = $this ->tmpfile(); |
5 |
exec ( "pdftk {$this->pdfurl} dump_data_fields > {$tmp}" ); |
6 |
$con = file_get_contents ( $tmp ); |
8 |
return $pretty == true ? nl2br ( $con ) : $con ; |
Create the FDF file
Let’s come to the phase where we will learn how to generate a FDF file. Let’s look at the coding part below
03 |
public function makeFdf( $data ) { |
06 |
1 0 obj<</FDF<< /Fields['; |
07 |
foreach ( $data as $key => $value ) { |
09 |
$fdf .= '<</T(' . $key . ')/V(' . $value . ')>>' ; |
16 |
$fdf_file = $this ->tmpfile(); |
18 |
file_put_contents ( $fdf_file , $fdf ); |
Working with the file
Set the $flatten to straighten the document that can easily be accessed by the generate() method
3 |
public function flatten() { |
5 |
$this ->flatten = ' flatten' ; |
Fill out the form
2 |
private function generate() { |
3 |
$fdf = $this ->makeFdf( $this ->data); |
5 |
$this ->output = $this ->tmpfile(); |
7 |
exec ( "pdftk {$this->pdfurl} fill_form {$fdf} output {$this->output}{$this->flatten}" ); |
Save the file
Creating save method to save the file:
02 |
public function save( $path = null) { |
10 |
$dest = pathinfo ( $path , Directory_location_info); |
11 |
if (! file_exists ( $dest )) { |
13 |
mkdir ( $dest , 0775, true); |
15 |
copy ( $this ->output, $path ); |
17 |
unlink( $this ->output); |
18 |
$this ->output = $path ; |
Force download the file
02 |
public function download() { |
06 |
$filepath = $this ->output; |
07 |
if ( file_exists ( $filepath )) { |
08 |
header( 'Content-Description: File Transfer' ); |
09 |
header( 'Content-Type: application/pdf' ); |
10 |
header( 'Content-Disposition: attachment; filename=' . uniqid(gethostname()) . '.pdf' ); |
12 |
header( 'Cache-Control: must-revalidate' ); |
13 |
header( 'Pragma: public' ); |
14 |
header( 'Content-Length: ' . filesize ( $filepath )); |
Check if you have generated the file for download purpose. Send the content of the file to the output buffer by using PHP’s readfile() function.
You will now see that PdfConfig class is ready to use.
Putting the class into action
02 |
require 'PdfConfig.php' ; |
04 |
'employee_name' => 'Shikha' , |
05 |
'designation' => 'Content writer' , |
07 |
$pdf = new PdfConfig( 'form.pdf' , $data ); |
Create FDF file
2 |
require 'PdfConfig.php' ; |
4 |
'employee_name' => 'Shikha' , |
5 |
'designation' => 'Content writer' , |
7 |
$pdf = new PdfConfig( 'form.pdf' , $data ); |
8 |
$fdf = $pdf ->makeFdf(); |
Extract PDF field information
You need to access the following code at the time of extracting your PDF field information. Let’s have a look on them:
2 |
require 'PdfConfig.php' ; |
3 |
$data_fields = new PdfConfig( 'form.pdf' )->fields(); |
We can pass this with the fields() technique, to empower a comprehensible yield structure:
2 |
require 'PdfConfig.php' ; |
3 |
$pdf = new PdfConfig( 'pdf-test.pdf' )->fields(true); |