cakephp4にてPDF出力する方法

たびたび苦労するのでメモしておきます。今回の環境としては、CakePHP4.0.8です

まずは、TCPDFをcomposerでインストールします。

/var/www/html # composer require "tecnickcom/tcpdf"
Using version ^6.3 for tecnickcom/tcpdf
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 1 install, 0 updates, 0 removals
  - Installing tecnickcom/tcpdf (6.3.5): Downloading (100%)         
Package phpunit/php-token-stream is abandoned, you should avoid using it. No replacement was suggested.
Writing lock file
Generating autoload files
> Cake\Composer\Installer\PluginInstaller::postAutoloadDump
24 packages you are using are looking for funding.
Use the `composer fund` command to find out more!

あとは、プログラミングだけですが、DebugKitを使っていることを忘れることが多くあります。確実に動作しないように設定しておきます。

// controllerにて

use Cake\Core\Configure;

class ExamplesController extends AppController
{
    public function pdf出力アクション()
    {
        Configure::write('debug', false); // debugkitが動作しないように設定
        $this->set(compact(['data1', 'data2']));   //これは適当に
        $this->viewBuilder()->enableAutoLayout(false);   // layoutファイルを使わないように
        $this->response = $this->response->withType('pdf'); 
        $this->response->withType('application/pdf'); 
        $this->response->withCharset('UTF-8');
        return;
    }
}

コメント

タイトルとURLをコピーしました