LoginSignup
1
0

More than 1 year has passed since last update.

CakePHP で mPDF を使う

Last updated at Posted at 2021-05-13

こちらの記事と同様のことを Ubuntu 21.04 で行いました。
CakePHP 4 に mPDF 8 を導入してテンプレートから PDF を生成

プロジェクトの作成

composer create-project --prefer-dist cakephp/app:4.2.* sample-project

サーバーの起動

cd sample-project/
bin/cake server

起動の様子

$ bin/cake server

Welcome to CakePHP v4.2.6 Console
-------------------------------------------------------------------------------
App : src
Path: /home/uchida/lang/php/cake/sample-project/src/
DocumentRoot: /home/uchida/lang/php/cake/sample-project/webroot
Ini Path: 
-------------------------------------------------------------------------------
built-in server is running in http://localhost:8765/
You can exit with `CTRL-C`
[Thu May 13 17:14:26 2021] PHP 7.4.16 Development Server (http://localhost:8765) started

http://localhost:8765 にアクセス
cakephp_may13.png

mPDF のインストール

composer require mpdf/mpdf

TakaoMincho.ttf のシンボリックリンクを作成

mkdir data
mkdir data/font
cd data/font
ln -s /usr/share/fonts/truetype/takao-mincho/TakaoMincho.ttf .

PDF を出力するプログラム

src/Controller/SampleController.php
<?php
declare(strict_types=1);

namespace App\Controller;

use Mpdf\Mpdf;

class SampleController extends AppController
{
  public function index()
  {

  $mpdf = new Mpdf([
    'fontDir' => [ROOT . DS . 'data' . DS . 'font'],
    'fontdata' => [
      'takao' => ['R' => 'TakaoMincho.ttf'],
    ],
    'default_font' => 'ipa',
  ]);

    $html = '<h1>こんにちは、世界!</h1>';
    $html .= '<blockquote>';
    $html .= 'May/13/2021 PM 17:03<br />';
    $html .= '</blockquote>';
    $mpdf->WriteHTML($html);
    $encodedName = rawurlencode('sample001.pdf');

    return $this->response->withType('pdf')
      ->withHeader('Content-Disposition', "attachment;filename*=UTF-8''{$encodedName}")
      ->withStringBody($mpdf->Output('', 'S'));
  }
}
templates/Sample/my_pdf.php
<html>
  <head>
    <?= $this->Html->css(['sample/my_pdf.css']) ?>
  </head>
  <body>
    <h1><?= $title ?></h1>
    <p>Sample</p>
    <p>サンプル用のPDFです</p>
  </body>
webroot/css/sample/my_pdf.css
h1 {
  color: #f00;
}

サーバーを起動して、
http://localhost:8765/Sample
にアクセスする
cakephp_mpdf_may13.png

次の環境で確認しました。

$ php -v
PHP 7.4.16 (cli) (built: Mar 23 2021 16:15:03) ( NTS )
Copyright (c) The PHP Group
Zend Engine v3.4.0, Copyright (c) Zend Technologies
    with Zend OPcache v7.4.16, Copyright (c), by Zend Technologies

$ composer --version
Composer version 2.0.9 2021-01-27 16:09:27
1
0
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
1
0