How to dynamically generate PDF files from HTML using PHP

Yesterday only a client got me in a situation where we we need PDF files to generated dynamically. As I went on with some research, I got to know about this awesome PHP library called mPDF. It is a vast library with almost all the required features and on top of it, it is GPL or free, in layman’s word.

Link for mPDF official website

As it had all the functions to print images or text on PDF files, but being a web developer I am always comfortable with markup layout. So I chose to use its HTML to PDF conversion abilities over custom functions. Below is the  code that shows how easy it become for me to convert generate PDFs:-

 

[php]

include “mpdf/mpdf.php”;

$html = ‘<html>
<head>
<title></title>
</head>
<body>
<h2>Heading</h2>
<hr>
<p style=”background:#cacaca; padding:50px;”>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Porro, dicta, reiciendis voluptatum commodi architecto dolore libero doloribus eum omnis earum. At, nulla, tempora, nam, quisquam placeat accusamus optio ducimus quasi itaque vel reprehenderit omnis dolores corrupti voluptas modi? Odit dignissimos ratione omnis alias asperiores natus tenetur debitis libero ad sint.
</p>
<img src=”gplus_bckgrd.jpg” alt=”” style=”width:100%”>
</body>
</html>’;

$mpdf=new mPDF($html);
$mpdf->WriteHTML($html);
$mpdf->Output(“test.pdf” , “F”);
header(“location:test.pdf”);
exit;

[/php]

Conclusion

mPDF library is certainly has its worth in gold. I would recommend it to you over any other library for the same task.

 

2 Comments

  1. Rachid-Reply
    February 26, 2015 at 12:06 pm

    Hi

    Thanks for this plugin, but the authors of website can not use it.

Leave A Comment