如何在cakephp 2.0中使用Fpdf创建pdf?

时间:2012-02-06 12:15:35

标签: cakephp 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目录中。

2 个答案:

答案 0 :(得分: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');
}

答案 1 :(得分: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