views:

79

answers:

1

How can I make something like this with Zend_PDF:

I have a few columns A, B, C, D, E and after them I will have some information, something like excel.

A | B | C | D

ss|das|dad|ds

ss|das|dad|ds

ss|das|dad|ds

How can I create something like this with ZF_pdf? I will pull the data from DB, can you please give me an example?

+1  A: 

This is a very simple working example that loads data from a file and creates a PDF from that:

require_once 'Zend/Pdf.php';

$pdf = new Zend_Pdf();
$page = new Zend_Pdf_Page(Zend_Pdf_Page::SIZE_A4);
$font = Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_HELVETICA);

define('FONT_SIZE'      , 12);
define('MARGIN_LEFT'    , 40);
define('MARGIN_TOP'     , 40);
define('COL_WIDTH'      , 100);
define('COL_LEFT_MARGIN', 10);
define('COL_SEPARATOR'  , '|');
define('ROW_HEIGHT'     , 20);

$row = 1;
$x = MARGIN_LEFT;
$y = MARGIN_TOP;

$page->setFont($font, FONT_SIZE);

if (($handle = fopen('data.csv', 'r')) !== false) {
    while (($data = fgetcsv($handle, 1000, ",")) !== false) {
        $num = count($data);
        $row ++;
        for ($i = 0; $i < $num; $i++) {
            $page->drawText($data[$i], $x, $page->getHeight() - $y);
            $x += COL_WIDTH;
            $page->drawText(COL_SEPARATOR, $x, $page->getHeight() - $y);
            $x += COL_LEFT_MARGIN;
        }
        $x = MARGIN_LEFT;
        $y += ROW_HEIGHT;
    }
    fclose($handle);
}
$pdf->pages[] = $page;
$pdf->save('data.pdf', true);

Where the CSV file contains arbitrary data, e.g.:

"A","B","C","D"
"asd","daasd","sdfs","dfsdf"
"asd","daasd","sdfs","dfsdf"
"asd","daasd","sdfs","dfsdf"

Of course, the data source could be anything else. Note that this example is not able to deal with large strings, multiple pages, etc.

nuqqsa
I also need to have multiple pages and so on.Can you help to adapt this?I'm new to Zend_PDF and the new ZF docs..are so bad...so I can't do it on my own.
Uffo
You have to use the dimensions of the page and the position of the cursor to figure out when to start a new page. `$page->getHeight()` and `$page->getWidth()` give you the height and width of the page, which are corresponding to the standard dimensions assigned when creating it (A4 in this case). For instance, if each line is 20px high and there's a margin of 40px at the top and the bottom of the page, you know that there's space for (842-40*2)/20 lines (where 842 is the height of the A4). Pages are added with `$pdf->pages[] = $page;`. IMO the documents are comprehensive enough to do this.
nuqqsa
Thx a lot man! I will try this out!
Uffo