Friday, July 22, 2011

Creating simple pdf documents with Zend Framework

The Zend_Pdf component is a "pure PHP" implementation of the PDF standard, and no external libraries are required to use it. This can come in handy when operating in a shared hosting environment that does not allow individual access to custom extensions. The component supports most common PDF operations, including adding and deleting pages; inserting text and images on pages; drawing and colorizing shapes; and updating document meta-data.

Let's begin with a simple example :

// create PDF
  $pdf = new Zend_Pdf();
  
  // create A4 page
  $page = new Zend_Pdf_Page(Zend_Pdf_Page::SIZE_A4);
  
  // define font resource
  $font = Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_HELVETICA);
  
  // set font for page
  // write text to page
  $page->setFont($font, 24)
       ->drawText('That which we call a rose,', 72, 720)
       ->drawText('By any other name would smell as sweet.', 72, 620);
  
  // add page to document
  $pdf->pages[] = $page;
  
  // save as file
  $pdf->save('example.pdf');

If you'd like to insert an image into the PDF document, this is easily accomplished with the drawImage() method, which accepts a Zend_Pdf_Image resource and a set of coordinates, and then writes the image to that position in the document. JPEG, PNG and TIFF images are currently supported, and the system will auto-detect the image type based on the file extension. Here's an example of it in use:
// create PDF
  $pdf = new Zend_Pdf();
  
  // create A4 page
  $page = new Zend_Pdf_Page(Zend_Pdf_Page::SIZE_A4);
  
  // define image resource
  $image = Zend_Pdf_Image::imageWithPath('IMG_007.jpg');
  
  // write image to page
  $page->drawImage($image, 50, 50, 400, 400);
  
  // add page to document
  $pdf->pages[] = $page;
  
  // save as file
  $pdf->save('example.pdf'); 

No comments:

Post a Comment