2012-02-06 69 views
3

我实际上已经非常远,但我的输出是乱码,没有格式化的PDF,因为我预期。下面是相关代码:如何在cakephp 2.0中使用Fpdf创建pdf?

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'); 

} 

查看/设计/ pdf.ctp:

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

查看/职位/ pdf.ctp:

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

,FPDF安装在root/Vendors目录中。

回答

1

变化的响应类型:

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'); 
} 
0

在cake2你可以使用一个更简洁的方法 - 有或没有新的响应对象: http://www.dereuromark.de/2011/11/21/serving-views-as-files-in-cake2/

标头将蛋糕本身从控制器进行设置。 这是不好的编码(再也不是)在布局中设置它们(我曾经这样做,以及^^)。

这几天CakePdf plugin已经成熟为一个非常有用的PDF生成工具。 我推荐在Cake2.x中使用它。

查看您的控制器功能http://www.dereuromark.de/2014/04/08/generating-pdfs-with-cakephp

+0

新响应对象的详细信息请参见http://book.cakephp.org/2.0/en/controllers/request -response.html#cakeresponse – mark 2012-02-06 15:26:36

+0

不,我不能让这个工作。另外我使用的FPDF不是DOMPDF,但我尝试了两个包。它建议尝试从控制器上的相同动作中加载pdf视图,这让我感到困惑。 – khany 2012-02-06 17:38:37