Generating PDF files with PHP

May 2nd, 2012 Leave a comment
Like the article?
Generating PDF files with PHP

If you are looking for a way to convert HTML to PDF, check out this post. This article continues the PDF series but addresses a slightly different task. In PHP, generating files is easy, but sometimes you need to have complete control over the content generation such as how documents are generated for printing. This is when using PDF files is handy because they give you a greater amount of control than HTML or other document types. Here, I will walk you through how to create PDF files dynamically using PHP a free tool called Free PDF library (FPDF) that will help you take control of your content.

Since controls or APIs for using PDF documents are not part of the PHP core, you will need to use a third-party tool to accomplish this. The one I have chosen for this tutorial is the Free PDF Library (FPDF) which is in native PHP and doesn’t require any compilation. This is a completely free tool so you do not have to worry about licensing or limitations. For this tutorial, we will use an XML data file to format our PDF documents. The following is a sample of our XML plant data we will be using:


<?xml version="1.0" encoding="ISO-8859-1"?>
	<plant name="Bloodroot">
		<info type="Sanguinaria canadensis" zone="4" light="Mostly Shady" price="$2.44"/>
	<plant name="Columbine">
		<info type="Aquilegia canadensis" zone="3" light="Mostly Shady" price="$9.37"/>
	<plant name="Marsh Marigold">
		<info type="Caltha palustris" zone="4" light="Mostly Sunny" price="$6.81"/>

The root element for this XML document is the CATALOG tag and data is grouped by the PLANT tag, which holds various information about the types of plants and the price of each. The following is the PHP code that we will use to read the XML document into a DOMDocument object:


function getInfo() {
  $xml = new DOMDocument(); 
  $plants = array();
  foreach($xml->getElementsByTagName('PLANT') as $plant) { 
    $infos = array();
    foreach($plant->getElementsByTagName('INFO') as $info) {
      $infos[] = array(
        'type' => $info->getAttribute('type'),
        'zone' => $info ->getAttribute('zone'),
        'light' => $info ->getAttribute('light'),
        'price' => $info ->getAttribute('price')

    $plants [] = array(
      'name' => $plant->getAttribute('name'),
      'info' => $infos

  return $plants;

This script calls the getInfo function while reads the XML file into a DOMDocument object which can then traverse the plant catalog and get each element for each plant. This will essentially create an in-memory version of the XML document. To test that your PHP script works, you could create a test HTML output document that will build HTML tables for the data. This way you can view if the data is being read in correctly. Here is the test HTML for our script:


$results = getInfo();
foreach ($results as $plant) { ?>
<h1><?php echo($plant['name']) ?></h1>

foreach ($plant['info'] as $info) {
  $s1 = $info ['type'];
  $s2 = $info ['zone'];
  $s3 = $info ['light'];
  $s4 = $info ['price'];
<td><?php echo($s1) ?></td>
<td><?php echo($s2) ?></td>
<td><?php echo($s3) ?></td>
<td><?php echo($s4) ?></td>

When we view this page we should see the XML data file that has been processed rendered as HTML tables. Here is what this should look like:

HTML tables

Next, now that we know we can read in our data, we will build the PDF. The first step is to download the FPDF library and install it in the same directory as our application files. You can get the library from here:

Be sure to keep track of where you put the FONT directory since we will need to make a configuration change to the FPDF_FONTPATH as shown below:



$pdf = new FPDF();
$pdf->SetFont('Arial', '', 72);
$pdf->Cell(40, 10, "Hello World!", 15);

This script calls upon our new library and generates a “Hello World” document to test that we have everything set up correctly. The first thing the script does is set the location of the FONT directory and then call the fpdf.php file to begin creating our PDF document. As you can see, we have set the output font family to Arial and the size to 72. If you do not see the PDF document, you will need to check that your file paths are correct to these files.

If the PDF “Hello World” is working OK, is now time to combine this with our plants document to generate a PDF of our XML.



class PDF extends FPDF {
  function PlantTable($plant) {
    $this->Cell(40, 10, $plant['name'], 15);

$pdf = new PDF();
$pdf->SetFont('Arial', '', 30);

foreach (getInfo() as $plant) {


To start, we have extended the FPDF class with our own subclass and created a new method called PlantTable that will build our table of plants. Here is what your output should look like right now:

your  output

Each plant name should be its own heading on a new page because we have wrapped this in a foreach loop and added in the AddPage() method, which will generate a new page for each heading. Now we can build the plant table to show the data for each plant. We basically need to build each cell of the table and define widths, fonts, fill color, line color etc. In this section we have set up the header bar for the table.



class PDF extends FPDF {
  function EventTable($plant) {
    //create the name of the plant
    $this->SetFont('', 'B', '24');
    $this->Cell(40, 10, $plant['name'], 15);

    //set up the headers
    $this->SetXY(10, 45);

    $this->SetFont('', 'B', '10');
    $this->SetFillColor(128, 128, 128);
    $this->SetDrawColor(92, 92, 92);

    $this->Cell(70, 7, "Type", 1, 0, 'C', true);
    $this->Cell(20, 7, "Zone", 1, 0, 'C', true);
    $this->Cell(70, 7, "Light", 1, 0, 'C', true);
    $this->Cell(20, 7, "Price", 1, 0, 'C', true);

$pdf = new PDF();

foreach (getInfo() as $plant) {


The additional code (marked with the comment “set up the headers”), allows us to render the cells for the four column headers. It then uses the Ln method, which performs a carriage return to a new line. Here is what the column headers look like:

column headers

Now we can create the plant information inside of our table and complete our document.


  //create rows of plant data
  $this->SetFillColor(224, 235, 255);

  $fill = false;

  foreach($plant['info'] as $info) {
    $this->Cell(70, 6, $info['type'], 'LR', 0, 'L', $fill);
    $this->Cell(20, 6, $info['zone'], 'LR', 0, 'L', $fill);
    $this->Cell(70, 6, $info['light'], 'LR', 0, 'L', $fill);
    $this->Cell(20, 6, $info['price'], 'LR', 0, 'L', $fill);

    $fill =! $fill;

  $this->Cell(180, 0, '', 'T');

Now we have created a row for each set of plant information found. This is wrapped in a foreach loop so if you have more than one set of plant info in the XML document it will create a new row. Here is how our document should look now:

a new row

As you can see, we have used a $fill variable to determine the color that should be used for reach row. This is what toggles the alternate color of each, as you can see on the last page since there are two rows:

two rows

To spruce up the PDF document, you may want to add in some graphics. I grabbed a picture of some bloodroot to add to the document and added the following lines to the code at the start of the PlantTable method:

$this->Image('bloodroot.jpg', 5, 5, 33);
$this->SetXY(40, 15);

Here is our new document with the image:

new document with the image

As you can see, the Image method takes a file name, location, and a width. The new SetXY call allows the image to not be overwritten by the heading text. There are other methods available that will allow you to manage graphics, add flowing text, hyperlinks and manage page mechanics. The library gives you full control over your generated PDF document.

I hope you have found this tutorial useful in creating your own PDF documents. As you can see, with the right tool this is an easy thing to accomplish and is ideal if you need to create invoices, tickets, forms or any other printed document as well as anything where you need exact control of the layout and content. To try this code out on your own, you can download the source from here.

Article Source Files

DescriptionNameSizeDownload method
Generating PDF files with PHP Source Codepdf-php-sources.zip1KBHTTP
Help us spread the word!
  • Twitter
  • Facebook
  • LinkedIn
  • Pinterest
  • Delicious
  • DZone
  • Reddit
  • Sphinn
  • StumbleUpon
  • Google Plus
  • RSS
  • Email
  • Print
Don't miss another post! Receive updates via email!