Dynamic PDFs with the Zend Framework

March 20th, 2006

No, please no! Not another framework! Yes, exactly my reaction until I found out how nice and modular the newly released Zend PHP Framework is. Normally you get locked into doing things the “framework’s way” but refreshingly you can just drop in classes as you need them. Hopefully things will stay that way…

Before you go on check you’ve got PHP 5: the caveat of the framework I’m afraid.

Anyway, I happen to need PDF generation support, the context is irrelevant, but this shows you how easy it is. The Zend demo only goes so far in telling you how to generate PDFs as it only works from the command line. Here’s how to cook ‘em up for your browser! First up make sure you’re including the class properly, have a look at the documentation if you’re unsure as to what I’m doing. My require path goes like this:

require_once 'Zend/Pdf.php

Next it’s just a case of following the documentation to get your desired result. Here’s a little something to get you going:

$pdf = new Zend_Pdf();
$pdf->pages[] = ($page1 = $pdf->newPage('A4'));
$font = new Zend_Pdf_Font_Standard(Zend_Pdf_Const::FONT_HELVETICA);
$page1->setFont($font, 36);
$page1->drawText('Invoicer', 10, 800);
$page1->setLineWidth(0.5);
$page1->drawLine(10, 800, 570, 800);
$bodyfont = new Zend_Pdf_Font_Standard(Zend_Pdf_Const::FONT_HELVETICA);
$page1->setFont($bodyfont, 12);
$page1->drawText('Mr Alexander Biddle', 400, 780);
$page1->drawText('10 Blarsdale', 400, 760);
$page1->drawText('Blardolk', 400, 740);
$page1->drawText('Murdolk', 400, 720);
$page1->drawText('Foobarch', 400, 700);
$page1->drawText('This is a invoice', 10, 680);

Right, you should manage to get something like that from gleaning the docs, but the next bit I couldn’t see there; how to output the PDF to the browser. It’s quite easy though, just use the render() member function, which returns a string:

$pdfString = $pdf->render();

You can then echo out this string with the appropriate headers so that the browser treats it as a PDF file:

header('content-type: application/pdf');
header('content-Disposition: inline; filename=invoicer.pdf');
echo $pdfString;

Nicely done!

Comments are closed.