LoginSignup
15
15

More than 5 years have passed since last update.

CakePHP3でPDFファイルを出力する

Posted at

CakePHP3でTCPDFを使ってPDFファイルを作成しダウンロードさせます。

composer.jsonのrequireにTCPDFを追加してcomposer updateする。

composer.json
{
    "require": {
        "tecnick.com/tcpdf": "*"
    }
}

ControllerにMIMEタイプとかファイル名とかのresponseを記述する。
(以下、領収書を出力するような例です。)

PaymentsController.php
public function receipt($id = null)
{
    $payment = $this->Payments->get($id);
    $this->set(compact('payment'));
    ・・・
    $this->response->type('pdf');
    $this->response->charset('UTF-8');
    $this->response->download('receipt.pdf');
    $this->layout = false;
}

テンプレートにて、HTMLで書いた内容をwriteHTML()でPDF化してechoする。
(TCPDFの設定等についてはTCPDFのドキュメント等を見てください。)

Payments/receipt.ctp
<?php
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8');
$pdf->SetFont('kozgopromedium');
$pdf->setPrintHeader(false);
$pdf->setPrintFooter(false);
$pdf->AddPage();

$html = <<< EOF
<html>
<head>
    <style type="text/css">
    h1 {
        text-align: center;
    }
    </style>
</head>
<body>
<h1>領収書</h1>
<table>
・・・
</table>
</body>
</html>
EOF;

$pdf->writeHTML($html, false);
echo $pdf->Output('', 'S');
?>

Controllerで$this->response->download('receipt.pdf')を書かずに、テンプレートで$pdf->Output('receipt.pdf', 'D')としてもできますが、Testがうまくいかなくなるので、Sでechoすることにしました。

15
15
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
15
15