Thursday, June 2, 2011

Generating PDF documents from PHP


Sometimes we want to generate pdf files from php for purposes like report generations. The solution I found for that is to use the MPDF library which can be obtained from here. The online documentation they have provided in MPDF website is very useful. However I just used very few functionalities of it for my purpose. Here I write down a small example that You can extend for your particlular requirement.

First download the MPDF libray and uncompress it. Put it in the apache servers web directory. Now open your favourite text editor and include the following somple codes.

1:  <?php  
2:       // The path to mpdf.php file inside your uncompressed mpdf directory  
3:       include('./mpdf51/mpdf.php');  
4:       // Create an object of mPDF class  
5:       $mpdf=new mPDF();  
6:       // Use this function to put html outputs in pdf file.  
7:       $mpdf->WriteHTML("<h1>Hello World</h1>");  
8:       // This function will create the pdf file.   
9:       $mpdf->Output();  
10:       exit;  
11:  ?>  

This simple code can be changed for creating different outputs. What you have to do is just put html formattings in a string and pass it to this $mpdf->WriteHTML() function. Please note that you have a lot of functions for creating and formatting the pdf files output. This $mpdf->WriteHTML() function is actually misused in my code for generating different things like tables, and other formattings. But I used this function only because it just involves my html knowledge for creating the formattings. However if you really want to learn and use the options provided by MPDF, you better look at the MPDF manual from here.