如何使用FPDF在Cakephp中渲染视图

时间:2014-08-23 01:23:01

标签: cakephp-2.3 fpdf

我在使用cakephp中的基本pdf文档时遇到一些困难。 (我感兴趣的是动态渲染视图,而不是下载pdf。) 这就是我所做的,我只是得到一个pdf乱码。

gibberish

在Vendor文件夹中添加了fpdf类文件。 (供应商自动加载,我可以访问该类)

创建app / View / Layouts / pdf.ctp

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

创建控制器操作:

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

创建匹配的document.ctp查看上述控制器操作:

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

在我尝试过的配置/路由中没有这个......

Router::parseExtensions('pdf');

我哪里错了? 这一切在非cakephp环境中运作良好。

2 个答案:

答案 0 :(得分:0)

原来我非常接近。 我被告知以上实际上适用于旧版本的cakephp(即1.3)。 我没有验证,因为我没有使用任何旧版本。

首先关闭...在我的情况下不需要配置文件修改。

从布局中删除:

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

添加到控制器:

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

所以简单地将内容类型声明从布局移动到控制器对我来说是个窍门。

希望这有助于某人。

答案 1 :(得分:0)

这种方式对我有用:

  1. 在控制器上,在命名空间之后,输入:
  2. require_once ROOT . DS . 'src/Lib/fpdf/fpdf.php';
    1. 现在,在函数中:

       function responsiva_celulares($id) { //Name of the view
          $this->layout = '';        //Removing layout
          $this->set('id', $id); //Some variables
          $this->render()->type('application/pdf'); //Rendering the pdf
      }
      
    2. 然后,在responsiva_celulares.ctp中:

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