Saturday, October 13, 2012

Convert HTML to PDF Easy and Simple With mPDF

| 2 comments

Sometimes we need to generate reports to PDF for printing or archiving. Perhaps, you may have experienced with creating a PDF in PHP but there are a lot of configurations and complicated command just to make a table. after a long search, I found mPDF library to easily generate HTML script to PDF, and my favorite part is its support to css. You can download it free at this link. In this post, I'll show you how to use it.



Assume we have a xampp web server, so we will have an htdocs folder as the server directory. Extract the mPDF (zip file) to the folder inside the htdocs directory called convert (or whatever you want). There should be some files and folders. The figure below is the minimum file requirement that should be in the 'convert' directory.


mpdf library files
mpdf library files that should be exist
then in the same folder, create a php file called test.php.
Copy and paste the script below then you can change it to be suitable with your needs.
<?php
// set the text, including table or image to print as PDF
$html = "This just for testing only, you can change it. <br />
<img src=\"baby.jpg\" style=\"float:left;\"/> The image on the side named baby.jpg<br /> ";
// here we go
include("mpdf.php");
// see the constructor method in mpdf.php file, there is a complete explanation, or you can see its documentation.
// A4 means we use A4 Paper
$mpdf = new mPDF('utf-8', 'A4', 0, '', 10, 10, 5, 1, 1, 1, '');
$mpdf->WriteHTML($html);
$mpdf->Output();
?>

The result will be similar to this image

Hope this post useful.


2 comments:

  1. great tool
    thanks for sharing

    ReplyDelete
  2. I am surely going to recommed your blog to more and more people. If you want to convert JPG into PDF then try this JPG to PDF converter. This JPG to PDF converter from PDF online can prove to be your best help.

    ReplyDelete