Convert html to pdf in php using mpdf

Html to pdf

If your php application needs to generate some kind of pdf report then the simplest approach would be to generate the report as an html and then convert it to pdf using some library. Plenty of libraries are available that can convert html to pdf in php. To name a few - fpdf, tcpdf, mpdf etc. I found mpdf to be the best library for html to pdf conversion inside php. It is written in pure php, does not require any external library and has excellent support for css.


Mpdf can be downloaded from Also check out the examples and the documentation.

Features include

- UTF-8 encoded HTML
- Almost all languages including RTL (arabic and hebrew), and CJK - (chinese-japanese-korean)
- Bookmarks
- CSS stylesheets
- Embedded font subsets
- Word spacing and character spacing for justification
- Nested block-level elements (e.g. P, DIV) including margins, borders, padding, line-height, background colours etc.
- Page layout and orientation
- Page numbering
- Odd and even paging with mirrored margins
- Page headers & footers
- Columns
- Tables - nested tables, rotated, or autosized to fit on a page
- Text-justification and hyphenation
- Table of contents
- Index
- Watermarks
- Password protection.

When converting html to pdf, the resulting pdf often deviates from the original html in its appearance to a certain extent. The pdfs generated by mpdf resemble the original html very much and if coded correctly taking into account certain restrictions, it is possible to make the pdf look exactly identical to the original html.

Mpdf can also generate a wide range of 1d barcodes like code39, isbn etc. So overall its an excellent solution for quick and handy html to pdf conversion.

I have written a small helper function that quickly converts html content and saves it as pdf. Here it is

function html_to_pdf($html , $page = 'A4')
	//Now generate pdf from html
	//A4 paper
	$mpdf = new mPDF('utf-8' , $page , '' , '' , 0 , 0 , 0 , 0 , 0 , 0); 
	$mpdf->list_indent_first_level = 0;	// 1 or 0 - whether to indent the first level of a list

Here is a sample pdf of an invoice that is generated by converting html to pdf.

To convert webpages to pdf for the purpose of taking screenshots, a different utility called wkhtmltopdf can be used which takes a browser type screenshot of the webpage using the webkit rendering engine.

Last Updated On : 12th March 2013

Subscribe to get updates delivered to your inbox

About Silver Moon

Php developer, blogger and Linux enthusiast. He can be reached at [email protected]. Or find him on

1 Comment + Add Comment

  • The problem with this library is that it will struggle with JavaScript and the latest HTML 5 dynamic components. You could however try a API such as GrabzIt’s HTML to PDF API:

Leave a comment

Connect with us