PHP Template based pdf generation

People love PDF’s , they do ! There is a good reason for it though .

  • Portability.
  • Security.
  • Reliability.
  • Authenticity with the help of digital signatures.
  • Acrobat reader has an update every time i drink coffee. I guess ppl like to view something with the reader, just to justify the lost time in updating the software.

With that said you probably understand the need to generate PDF’s programmatically. Yes !! there is a huge need and its mind blowing how happy a customer is when he knows your product can generate a PDF !!

Well !! my love for PDF was on and off ! Just when i started loving it , it used to behave like a 2 year old , at times  getting the simplest things done used to be daunting ! .As a developer there are many options , you can either develop a library from scratch or use third party ones or may be magically create pdf with the force..hmm.. .That mostly depends on the time line, if you know what i mean . Well ! of course i used an array of libs to get things done , but there were too many options to choose from . The rest of the blog is entirely on that !

Using php’s pdf

Check out the manual . Its a nightmare to say the least but then it depends on your requirement . Its considerable faster than the methods i’ll tell you later in the post.

HTML to pdf

This is generally the easiest one for a web-developer . You programmatically create a html file and convert in to an pdf. This too has an array of options . The two best i liked are

This is quite  simple . You basically have a template predefined , you fetch appropriate values  , create a output html and done .



<html>
	<title>
 		This is some title
	</title>
	<body>
		Company name and stuff
		<?php
			for($i=0;$i<count($values);$i++){
				echo "some stuff of" . $values[$i];
			}
		?>
		Some Thank you note for buying stuff at <?php $price ?>
	</body>
</html>

This would work when you have less dynamic elements in your template. You can further enhance the way you create the template buy using mustache framework . Using mustache framework you can ensure none of the main business logics creeps into you template code . You use the mustache framework to render the template and make sure you do not use any php code in the template. This greatly enhances the generic-ness of template . You can find the documentation here to understand more about the mustache framework. Example using mustache


<html>
	<title>
		This is some title
	</title>
	<body>
		Company name and stuff
			
{{#values}}
* {{.}}
{{/values}}
Some Thank you note for buying soap at {{price}} </body> </html>

Alright now that we have generated the html , the next step ? Generate the pdf !

Using dompdf we get the entire html content and render it using dompdf


<?php
require_once("dompdf_config.inc.php");

$html =file_get_contents('path_to_the_html_file');

$dompdf = new DOMPDF();
$dompdf->load_html($html);
$dompdf->render();
$dompdf->stream("output.pdf");

?>

wkhtmltopdf needs shell access , which is not available on most shared hosting . you can use exec in php to run the command but then there is always security issues to deal with! You should, to some extent, be aware of the security risks in using exec.


<?php
exec (wkhtmltopdf 'path_to_html_file' output.pdf);
?>

Thats it !!! Now you have a pdf rendered and the client is happy! Almost. Just almost.

You have a set of templates and you can generate pdf’s . Nice. Now Client wants different template every week .They start sending you how the pdf should looks like in a word file . Now you have to not only figure out what the client wants but also create the template(html,css,fetch values) . Now this can be tiresome ! very tiresome ! Awesomely painful to do something over and over again !

Template based

How else can you make it work ? The need for a quick dirty template based pdf generator is required ! How to do it ? I came up with this assembly line for generating pdf’s . This method allows the client to use any pdf they want. Which is a small step for us, but a gaint leap for them .Allow them to create pdf, with all fancy design, with their favorite editor. There is some prep work to be done for the pdf. Adding appropriate  form field . (follow the link to understand more about form fields).Create form fields in the pdf with name field corresponding to the key , this key will be replaced with a value. Once form fields are created, the pdf is ready to pass through the assembly line .

Next we create a fdf (follow link to unserstand more) file with possible key value pairs , this of course depends on the business logic .Its just a fancy name for key value pair that’ll be used to merge in the pdf.

To create a fdf file is quite simple .  Just use this function that will return back a string , save it programmatically to a with “.fdf” extension .



//$file = "pdf file name"
//$info[$key] =$value
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;
}

Now that we have created an fdf file we have to merge it with the prepared pdf file with form fields. TO do this i use a pdf stamper library

pdftk is an amazing library . it can do a array of useful pdf things . You’ll quickly fall in love with it .Now getting back to how to merge the pdf .


	exec ('path_to_pdftk' prepared.pdf fill_form 'path_to_fdf' output.pdf flatten );

flatten makes all the form fields read-only .

Alright now that i can generate pdf with any template with form fields . Lets get more greedy ! How do i add images . For example, i’d like to add customer’s photo on a receipt for some joyous purpose. OOoooOOo .. how do i do it ? Lets continue the assembly line ! lets stamp an image in the pdf . Now the trouble is we will have to edit the pdf which is a difficult task ! How do i do it ? , more libraries

here   are the libraries which clearly explain how to stamp the pdf . Check out the pdf.php in the git repository for the example.

This might not be the best way to do it ,but nevertheless, it works. If you have money to spend, then the best php library to use is

http://www.setasign.de/ . They  give you an array of solutions to generate pdf with php.

Yeah that’s quite a long post but i dearly hope this is useful .

 

5 thoughts on “PHP Template based pdf generation

Leave a Reply

Your email address will not be published. Required fields are marked *