Creating Pdf files using Zend Framework Zend_Pdf component

3 Dec

Zend Framework provide component Zend_Pdf for creating pdf files. It is very easy to use this component.
Let’s have a look how to create pdf file using Zend_Pdf component.
First create instance of Zend_Pdf as

$pdf = new Zend_Pdf();


If you want to load existing pdf file and make changes, write this instead

$pdf = Zend_Pdf::load(‘path/to/file.pdf’);

If you want to save the file, simply write

$pdf->save(‘path/to/file.pdf’);


This will save new file. To update already existing file, write

$pdf->save(‘path/to/file.pdf’,’true’);

Or you can render your pdf file in the browser as

$pdf->render();

To add pages to the pdf file

$pdf->pages[] = new Zend_Pdf_Page(Zend_Pdf_Page::SIZE_LETTER);


Or

$pdf->pages[] = $pdf->newPage(Zend_Pdf_Page::SIZE_A4);


To remove specific page from the document

unset($pdf->pages[$id]);

In order to write text to the page you will need the following code.

$page=$pdf->pages[0]; // this will get reference to the first page.

$style = new Zend_Pdf_Style();
$style->setLineColor(new Zend_Pdf_Color_Rgb(0,0,0));

$font = Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_TIMES);

$style->setFont($font,12);

$page->setStyle($style);

$page->drawText(‘example text here’,100,($page->getHeight()-100));

In the code above we first get reference to the first page. In the next line we create instance of Zend_Pdf_Style and then setLineColor.
Next we set font by using Zend_Pdf_Font class.
Next two lines set the font to style and set style to page.
That’s it we have now set font and style.
Now its time to write text to the pdf file.
$page->drawText() does the magic for us.
That’s it. Have fun.

4 Responses to “Creating Pdf files using Zend Framework Zend_Pdf component”

  1. Ani July 20, 2009 at 6:06 am #

    Give code is generate the PDF file but generated PDF file is not Opened.

  2. Andrea November 20, 2009 at 5:40 pm #

    You should save the file after all the operations…and it will open.

  3. Ecommerce Web Design June 8, 2010 at 9:36 am #

    Thanks this has been a great help in getting me started, were just starting working on developing more on the Zend Framework since using Magento extensive.

  4. JSC June 7, 2011 at 8:04 pm #

    Small typo error – single quote should be removed around true eg:

    This will save new file. To update already existing file, write

    $pdf->save(‘path/to/file.pdf’,true);

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: