Hi, my name is David Carr and I'm a PHP Developer.

Blog Archives Categories Authors About Me Open Source Books Contact Me

Sponsor Me

Help support the blog so that I can continue creating new content!

My Latest Book

Laravel: The Modular way

Learn how to build modular applications with Laravel Find out more

Generate a PDF from a web page

PHP & MySQL | Tutorials | Tools

David Carr

Generate a PDF from a web page

Easily convert a web page into a PDF with MPDF, this library makes it possible to take a webpage and turn it into a PDF viewable on the site or offer it as a download.

A handy place for to learn about MPDF is through the manual at http://mpdf1.com/manual

Download a copy of MPDF at http://www.mpdf1.com/mpdf/download

What is MPDF?

mPDF is a PHP class which generates PDF files from UTF-8 encoded HTML. It is based on FPDF and HTML2FPDF with a number of enhancements. I wrote mPDF to output PDF files 'on-the-fly' from my website, 
handling different languages. It is slower than the original scripts e.g. HTML2FPDF and produces larger files when using Unicode fonts, but support for CSS styles etc. has been much enhanced.

This tutorial will show you how easy it can be to use.

Create a file say generatepdf.php 

Include the library then create a new object, set the payout type and dimensions.
Next set the base path this is needed for the paths to images etc
Optionally include a stylesheet for the page and pass that to the page using writeHTML()
Next include the web page to be read from, parameters can be passed to the page using GETs.
Finally to show the pdf call the output method.

$mpdf=new mPDF('c','A4','','' , 0 , 0 , 0 , 0 , 0 , 0); 
$stylesheet = file_get_contents('http://www.domain.com/style/pdf.css');

That's those few lines you can generate the PDF by calling the file in this case generatepdf.php in the browser.

If instead of display the PDF you wanted to download it you specify that in the output method set the filename to be used and then a D flag which tells the page to download the PDF rather then display it.


There's much more to MPDF then this but that's all you need to get started. 

Copyright © 2009 - 2022 David Carr. All code MIT license. All rights reserved.