Search code examples
cakephp-2.3fpdf

How do I render a view in Cakephp using FPDF


I’m having some difficulty getting just a basic pdf document to render within cakephp. (I am interested in dynamically rendering the view, not downloading the pdf.) Here’s what I’ve done and I’m just getting a pdf gibberish.

gibberish

Added fpdf class files in the Vendor folders. (Vendors autoload and I have access to the class)

Created app/View/Layouts/pdf.ctp

 header("Content-type: application/pdf"); 
    echo $content_for_layout;

Created controller action:

public function document(){
  App::import('Vendor','Fpdf/fpdf');
  $this->layout = 'pdf'; 
  $this->render()
}

Created matching document.ctp View for the above controller action:

$fpdf = new FPDF();
$fpdf->AddPage();
$fpdf->SetFont('Courier','B',16);
$fpdf->Cell(40,10,'Hello world');
$fpdf->Output();

In the config/routes I have tried with and without this…

Router::parseExtensions('pdf');

Where am I going wrong? This all works so well in a non-cakephp environment.


Solution

  • Turns out I was pretty close. I've been told that the above actually works in older version of cakephp (ie 1.3). I didn't verify since I don't use any of the older versions.

    First off... the config file modification was not needed in my case.

    Deleted from the layout:

    header("Content-type: application/pdf"); 
    

    Added to the controller:

    $this->request->type('application/pdf');
    

    So simply moving the content-type declaration from the layout to the controller did the trick for me.

    Hope this helps someone.