Zend_PDF
Tuesday, March 8th, 2011The use of PDF documents to insure formatting to the end is almost universally understood. With the recent application that I have recently written and deployed for Larkin Mortuary there are some forms that already are PDF I just need to write info to the PDF and spit it out. For this application is not using Zend Framework completely. Just certain components. I use the Zend_PDF component here. Below is the php that opens, writes, and outputs the PDF document.
<?
//get our Zend stuff. Once we have gotten the Autoloader we can call Zend functions at will.
require_once ‘Zend/Loader/Autoloader.php’;
$autoloader = Zend_Loader_Autoloader::getInstance();
//Perform query and get information
$db = new PDO(‘mysql:host=localhost;dbname=dbname;’, ‘username’, ‘password’);
$db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );
$case_number = $_REQUEST['case_number'];
$stmt = $db->prepare(“SELECT * FROM tables WHERE case_number=?”);
$stmt->execute(array($case_number));
$f = $stmt->fetch();
//Load our PDF and start the manipulation
$document = ‘./forms/ssa-721.pdf’;
$pdf = Zend_Pdf::load($document); //<- this creates a new instance of the Zend_Pdf class and loads the existing document.
$page1 = $pdf->pages['0']; //<- with Zend_Pdf you must specify the page that we are working with
$width = $page1->getWidth();
$height = $page1->getHeight();
//set Document Meta Data
$pdf->properties['Title'] = “SSA721 of {$f['decedents_given_names']} {$f['decedents_last_name']} {$f['decedents_suffix']}”;
$pdf->properties['Author'] = “Larkin Mortuary”;
//We must specify the Font and its size that we will be writing with.
$font = Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_TIMES);
$page1->setFont($font, 12);
//Draw our text, we have a bunch of things to draw
$DecedentInfo1 = “{$f['decedents_given_names']} {$f['decedents_last_name']} {$f['decedents_suffix']}”;
$page1->drawText($DecedentInfo1, 54, 705, ‘UTF-8′); // All drawn text requires three options. The actual text, the left starting place, measured in points from the left, and the bottom starting place, measured in points from the bottom.
$pdfData = $pdf->render();
header(“Content-Disposition: inline; filename={$f['decedents_last_name']}ssa-721.pdf”);
header(“Content-type: application/x-pdf”);
echo $pdfData;
?>
There are some things that are kind of annoying with this. Each life must be put out one at a time. Further, text does not wrap but is put out as one long line. You must use another function to break wrapped text up and feed that to Zend_Pdf. Also, it would be really nice to be able to feed Zend_Pdf an html page, and have that parsed and output as PDF. In the meantime this is a pretty easy way to manipulate, save, and create pdf’s.
If anyone has any hints or tips with Zend_PDF I would love to hear it.
