Creating A Simple PDF With The Zend Framework

I’ve recently been playing with creating PDF documents for a project I’ve been working on.

I thought I’d share some of the knowledge I’ve gained in the hope it will help others.

I’ve been using the excellent Zend Framework as usual, and the Zend_Pdf component in particular. This is a pure PHP implementation of the PDF standard and it doesn’t require any other libraries to be installed to work.

A PDF document is text document that has been been designed by Adobe a way to create and share printable documents across multiple platforms. If you open a PDF document in a text editor, you can see the markup for yourself, however it’s not very user friendly. This is where Zend_Pdf comes to our aid.

Let’s create a simple A4 document, and say Hello World!.


<?php
// load the Zend Framework Autoloader.
ini_set("include_path","./library");
require_once 'Zend/Loader/Autoloader.php';
$loader = Zend_Loader_Autoloader::getInstance();
try {
// create a new PDF document.
$pdf = new Zend_Pdf();
// create the Helvetica font.
$font = Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_HELVETICA);
// create a new A4 sized page.
$page = new Zend_Pdf_Page(Zend_Pdf_Page::SIZE_A4);
// draw the text Hello World! to position 0,0 with the Helvetica font.
$page->setFont($font, 16)
->drawText('Hello World!',0,0);
// add the page to the pdf document.
$pdf->pages[] = $page;
// save the finished PDF to a file
$pdf->save('helloworld.pdf');
// catch any errors
} catch (Zend_Pdf_Exception $e) {
die('PDF error: ' . $e->getMessage());
} catch (Exception $e) {
die ('Error: ' . $e->getMessage());
}
?>

What’s going on? Well firstly I take advantage of Zend Frameworks autoloader to load in the required components.

Next I create an empty PDF document. A copy of the Helvetica font is prepared for use. We’ll need to add pages to this document, so after this we create a new A4 sized page. I’ve used A4 as that is the common paper size in Europe, but in the US letter size is the standard. This can be changed by using Zend_Pdf_Page::SIZE_LETTER instead of Zend_Pdf_Page::SIZE_A4.

Now I have a page, I want to add some text to it. This is easily achieved using the drawText method. This takes the text, and an X and Y position to draw it at. We do need to set the font first, let’s use the Helvetica font we defined earlier, and use size 16. I chose position 0,0 to write the text, this is the bottom left hand side of the page.

Finally, I add the page to PDF document, and save it.

If an error occurs, I catch this with my exception handlers.

Of course, in reality you’ll want o do a lot more than just write one line of text. Zend_Pdf allows you to do a lot more, such as adding images, drawing graphics, adding meta data. I’ll cover this in another post.

Leave a Reply