Uffo
Uffo

Reputation: 10046

Zend Framework PDF example to excel type

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.

Upvotes: 1

Views: 1564

Answers (1)

nuqqsa
nuqqsa

Reputation: 4521

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.

Upvotes: 1

Related Questions