以前のFPDF Helperへの質問を時々いただくが、最近はTCPDFを使っており、FPDF Helperはさっぱりメンテナンスしていないので、TCPDF Helperを紹介する。フォントデータが埋め込まれるため、ファイルサイズが大きくなるが簡単に使える。

(環境)

まず、/vendors に tcpdf をおく。/venders/tcpdf/tcpdf.php となるようにファイルを配置する。
/app/views/helpers/tcpdf.phpは次のとおり。

<?php
App::import('vendor', 'tcpdf/tcpdf');
class TcpdfHelper extends TCPDF {
    public $helpers = array();
    function __construct($options) {
        $defaults = array(
            'orientation'   => 'P',
            'unit'          => 'mm',
            'format'        => 'A4',
            'unicode'       => true,
            'encoding'      => "UTF-8",
        );
        $options =  (is_array($options)) ? am($defaults, $options) : $defaults;
        extract(am($defaults, $options));
        parent::__construct($orientation, $unit, $format, $unicode, $encoding);
    }
}
?>

次に日本語フォントを表示するための準備をする。PDFに埋め込んで配布できるIPAフォントを使う場合、IPAfont00203.zip内のファイルをとりあえず /vendors/tcpdf/fonts/IPAfont00203/ipag.ttf となるよう保存し、コマンドプロンプトから、以下を実行し、ipag.ctg.z・ipag.php・ipag.zを/vendors/tcpdf/fonts/に移動する。

\tcpdf\fonts\IPAfont00203>..\ttf2ufm\ttf2ufm.exe -a -F ipag.ttf
\tcpdf\fonts\IPAfont00203>php -q ..\ttf2ufm\makefontuni.php ipag.ttf ipag.ufm

コントローラは適当に作る。

<?php
class TestController extends AppController {
    public $uses = array();
    public $helpers = array('Tcpdf');
    public $layout = 'blank';

    public function pdf()
    {
    }
}


ビューはTCPDFのサンプルを流用して作成。http://localhost/test/pdf で日本語が出ればOK。

<?php
// set document information
$tcpdf->SetCreator(PDF_CREATOR);
$tcpdf->SetAuthor("Nicola Asuni");
$tcpdf->SetTitle("TCPDF Example 002");
$tcpdf->SetSubject("TCPDF Tutorial");
$tcpdf->SetKeywords("TCPDF, PDF, example, test, guide");

// remove default header/footer
$tcpdf->setPrintHeader(false);
$tcpdf->setPrintFooter(false);

//set margins
$tcpdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);

//set auto page breaks
$tcpdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

//set image scale factor
$tcpdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

//set some language-dependent strings
//$tcpdf->setLanguageArray($l);

//initialize document
$tcpdf->AliasNbPages();

// add a page
$tcpdf->AddPage();

// ---------------------------------------------------------

// set font
//$tcpdf->SetFont("dejavusans", "BI", 20);
$tcpdf->SetFont("ipag", "BI", 20);

// print a line using Cell()
$tcpdf->Cell(0,10,"Example 002",1,1,'C');
$tcpdf->Cell(0,10,"日本語テスト",1,1,'C');

// ---------------------------------------------------------

//Close and output PDF document
$tcpdf->Output("example_002.pdf", "I");
?>


TCPDFクラスをnewする際のオプションは、コントローラのヘルパー設定時に定義できる。
キーにヘルパー名、値に設定を入れる。

public $helpers = array('Tcpdf' => array('orientation' => 'L'));

おしまい。