Creating PDF’s Dynamically with PHP

Today I had a project that required me to tap into a preexisting gallery of images and generate a PDF document from those images. Lucky for me there was already an XML file pointing to all those images which made the job a tid bit easier. The workflow is as follows.

1. loop through the XML file and extract all the images and put them in a variable.

2. Use the variable to finish out the string to each Image
2. Push that info through Cezpdf class to do all the heaving lifting and create our PDF for us.
3. Test
4. We’re done.

Example of my XML Loop:

<?php
$imgStr = "../xml_data/images/";
$xmlFileData = file_get_contents("../xml_data/myGallery.xml");
$xmlData = new SimpleXMLElement($xmlFileData);
$file = $xmlData->image;
$gid = 0;

if( count( $file ) > 0 ) {
foreach ($file as $f) {

} else  {
no images found
}
}
?>

I then injected some Cezpdf code to into the loop to pickup on each image. The Cezpdf class is really simple to use and allows you to do some basic PDF functions quickly. I’m sure there is a billion ways to do the same thing maybe faster, lighter weight blah, blah, blah but, this worked just fine for me, in the time constraint that I was under.

Example of Full Script I used:

<?php
include ('class.ezpdf.php');
$pdf = new Cezpdf();
$pdf->addInfo("Title", "This is a cool PDF");
$pdf->addInfo("Author", "Taylor");
$pdf->selectFont('./fonts/Helvetica.afm');
$pdf->ezSetMargins(0,0,0,12);
$imgStr = "../xml_data/images/";

$xmlFileData = file_get_contents("../xml_data/myGallery.xml");
$xmlData = new SimpleXMLElement($xmlFileData);
$file = $xmlData->image;
$gid = 0;

if( count( $file ) > 0 ){
foreach ($file as $f) {

$pdf->ezImage($imgStr.$f->link,$width='0',$resize='width');
$pdf->addText(25,24,12,'Taylor's PDF');
$pdf->ezNewPage();

}

} else {

$pdf->ezText('No images found',50);
$pdf->ezText($f);

}

$pdf->ezStream();
?>

Ok so that’s it. I’m sure I could explain this further but just no time right now.
Cheers.

Leave a Reply

*