Search code examples
phppdfcakephpcakephp-2.0fpdf

How to create a pdf using Fpdf in cakephp 2.0?


I have actually got very far but my output is gibberish and not a formatted pdf as I expected. Here is the relevant code:

JobsController:

public function viewpdf() {
    App::import('Vendor', 'Fpdf', array('file' => 'fpdf/fpdf.php'));
    $this->layout = 'pdf'; //this will use the pdf.ctp layout

    $this->set('fpdf', new FPDF('P','mm','A4'));
    $this->set('data', 'Hello, PDF world');

    $this->render('pdf');

}

View/Layouts/pdf.ctp:

<?php
    header('Content-Disposition: attachment; filename="downloaded.pdf"');
    echo $content_for_layout;
?>

View/Jobs/pdf.ctp:

<?php
    $fpdf->AddPage();
    $fpdf->SetFont('Arial','B',16);
    $fpdf->Cell(40,10,$data);
    $fpdf->Output();
?>

with FPDF installed in the root/Vendors directory.


Solution

  • Change the response type in your controller function:

    public function viewpdf() {
    App::import('Vendor', 'Fpdf', array('file' => 'fpdf/fpdf.php'));
    $this->layout = 'pdf'; //this will use the pdf.ctp layout
    
    $this->response->type('pdf');
    
    $this->set('fpdf', new FPDF('P','mm','A4'));
    $this->set('data', 'Hello, PDF world');
    $this->render('pdf');
    }