Creating automatic PDFs with PHP, MySQL

January 18, 2010

My collaborative Irish dictionary, Irishionary.com, creates a nightly PDF version of the dictionary. A cron job calls a PHP script that generates the PDF. There are examples of great looking PDF publications and mine isn’t one of them ;) All the same, it’s not that hard to create your own PDF files though PHP scripts pulling information from your database if you wish. If you figure out how to make them look nice, let me know!

An example of a PDF created through my PHP script:

PDF generated by PHP

This is the automated PDF of the Irishionary.com dictionary.

mPDF is the PHP library to use for creating this PDF. There are lots of other libraries available, but it’s hard to find one that instantly suits. mPDF seemed to be good in several ways, especially given that you can style the PDF using CSS (Disclaimer: not all CSS tags are supported. Each sold separately. Batteries not included.) Another good reason to use it is that there are a range of fonts that you can use.

The official PDF to show off what mPDF is below. However, I will not allow you to see a full size version of it in the likely chance that it would negatively affect your view of humanity.

Official PDF example generated from PHP

Official show-off PDF by mPDF.

Stop messing around, let’s get coding. Download the mPDF library above, and put it somewhere in your web directory. Start editing a new script called mypdf.php.

Step 1

Include the library in your script.

define('_MPDF_PATH','./mpdf/');
include('./mpdf/mpdf.php');

Step 2

Initiate the object that will output the PDF for you.

$mpdf=new mPDF();

Step 3

Write some HTML to the PDF. This is where your literary prowess comes in handy.

$mpdf->WriteHTML('My PDFYes, this ebook was totally
worth $29.95 of your hard-earned cash.', 2);
$mpdf->SetFooter('Copyright: me.');

Step 4

Write the PDF to your file system. This step may require some permissions setting magic that your Auntie Maggy definitely couldn’t do. Check out the documentation for more pointers.

$file_path = $_SERVER['DOCUMENT_ROOT'].'/pdf/mypdf.pdf';
$mpdf->Output($file_path,'F');

Step 5

Either:

  1. Give away your PDF for the sake of humanity
  2. Charge $29.95 for your “Amazing — New York Times” and “Life changing — My Mammy” PHP-generated PDF.

About the author

Eoin develops software and runs an Internet-based business (more about me). Follow me on Twitter, and better yet contact me at e@eoinoc.net. © Eoin Ó Conchúir 2009-2014.

comments powered by Disqus