15
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Cakephp3 + TCPDF でpdf作成

Posted at

cake3とpdfで検索するとFriendsOfCakeのCakePdfってのがヒットするが、こいつが見事にCake3だと動いてくれない。どうも対応してないようだ。
ということでふつーにTCPDFでやることにした。

まず、composer.jsonに以下追加。

composer.json
		"tecnick.com/tcpdf": "*"

更新かける

sudo composer update

続いてPdfController.phpをつくって

src/controller/PdfController.php
<?php
namespace App\Controller;

use App\Controller\AppController;

/**
 * Pdf Controller
 *
 */
class PdfController extends AppController
{
	public function initialize()
	{
		parent::initialize();
		$this->loadComponent('RequestHandler');
	}

    /**
     * index method
     *
     * @return void
     */
    public function index()
    {
		$this->layout = false;
		$this->RequestHandler->respondAs('pdf', [
			// Force download
			//'attachment' => true,
			'charset' => 'UTF-8'
		]);
    }
}

あとビューも作る。

src/Template/Pdf/index.ctp
<?php
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8');
$pdf->SetFont('kozgopromedium');
$pdf->AddPage();

$html = <<< EOF
<div>日本語テスト</div>
EOF;
 
$pdf->writeHTML($html, false, false, false, false, 'L'); 
$pdf->Output('sample.pdf', 'I');

とりあえずこれで十分だ。

15
12
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
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?