PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, April 22, 2022

[FIXED] How do I render a view in Cakephp using FPDF

 April 22, 2022     cakephp-2.3, fpdf     No comments   

Issue

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.



Answered By - Steve Peterson
Answer Checked By - David Goodson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing