Generate a PDF from a web page

David Carr

Tutorials PHP & MySQL Tools

Table of Contents

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.

include("MPDF/mpdf.php");
$mpdf=new mPDF('c','A4','','' , 0 , 0 , 0 , 0 , 0 , 0); 
$mpdf->setBasePath('http://www.domain.com/');
$stylesheet = file_get_contents('http://www.domain.com/style/pdf.css');
$mpdf->WriteHTML($stylesheet,1);
$mpdf->WriteHTML(file_get_contents('http://www.domain.com/somepage'));
$mpdf->Output();

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.

$mpdf->Output("mynewfile.pdf",'D');

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

Read articles directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Copyright © 2006 - 2024 DC Blog - All rights reserved.