人気のPHP WEBアプリケーションフレームワークLaravelのTipsを記録していきます

Laravel で pdfテンプレートとhtmlと日本語フォントを使ってpdfを出力する

● Laravel で pdfテンプレートとhtmlを使ってpdfを出力する

pdfを出力する時に、全てをhtmlで書いてもいいのですが、ロゴなどはpdfテンプレートで使い回すという方法も便利なので紹介します。

1. composer パッケージ「fpdi」「tcpdf」「html-compress 」のインストール

composer require setasign/fpdi
composer require tecnickcom/tcpdf
composer require wyrihaximus/html-compress 

2. pdfテンプレートとhtmlをディレクトリに保存

格納場所 resources/pdf を作成します。

mkdir resources/pdf

ここに pdf と html をコピーします。以下のファイル名とします。

template_01.pdf
template_01.pdf.html

3. 日本語フォントファイル「源真ゴシック」をこちらからダウンロードする

http://jikasei.me/font/genshin/

明朝フォントはこちらの 源様明朝 がお勧めです。
https://github.com/ButTaiwan/genyo-font

格納場所 resources/fonts を作成します。

mkdir resources/fonts

ここに 拡張子が .ttf のフォントファイルをコピーします。

4. pdfテンプレートとhtmlを読み込んで出力

Laravelのコントローラーからpdf 出力

use setasign\Fpdi;
use TCPDF_FONTS;
	public function tcpdf()
	{
        $pdf = new Fpdi\TcpdfFpdi();
		// $pdf = new \TCPDF("L", "mm", "A4", true, "UTF-8" );	// pdf テンプレートを使わない場合はこちら

		$pdf->setPrintHeader(false);
		$pdf->setPrintFooter(false);
		$pdf->AddPage();

		// テンプレートPDFファイル読み込み
		$pdf->setSourceFile(resource_path('pdf/template_01.pdf'));
		$page = $pdf->importPage(1);
		$pdf->useTemplate($page);

		// フォント
		$font = new TCPDF_FONTS();

		// フォント:源真ゴシック
		// $font_1 = $font->addTTFfont( resource_path('fonts/ipag.ttf') );
		$font_1 = $font->addTTFfont( resource_path('fonts/GenShinGothic-Medium.ttf') );
		$pdf->SetFont($font_1 , '', 10,'',true);

		// テンプレートhtmlファイル読み込み
		$html = \File::get( resource_path('pdf/template_01.pdf.html') );
		$pdf->writeHTML( $html, $ln=false, $fill=0, $reseth=false, $cell=false, $align="L" );

	 	$pdf->Output("output.pdf", "I");
	 }

5. tcpdf について調べるなら

このサイトがとても便利です

http://tcpdf.penlabo.net/

6. tcpdf の 改行や空白スペースがスペースとして認識されてずれる問題

htmlをminifyしましょう

composer require wyrihaximus/html-compress 
$parser = \WyriHaximus\HtmlCompress\Factory::construct();
$html = $parser->compress($html);

7. TCPDF で使用できるCSSプロパティ

以下のcssプロパティが使用できます。スタイルを思った通りにするのにはかなり足りないと思います。

font-family
font-size
font-weight
font-style
color
background-color
text-decoration
width
height
text-align

ではレイアウトはどうすれば良いのか?

「line-height を使う」か「いにしえのテーブルレイアウトを使う」のがいいでしょう。

例: line-height を使う

<table border="0">
    <tr>
        <td style="font-size:18px;line-height:57px;">お名前 太郎</td>
    </tr>
</table>                

例: いにしえのテーブルレイアウトを使う

<html><body>
<table border="0">
	<tr>
		<td style="width:30px;"></td>
		<td style="width:350px; height:75px;"></td>
		<td></td>
	</tr>
	<tr>
		<td></td>
		<td></td>
		<td>平成31年1月25日</td>
	</tr>
</table>
</body></html>

● pdfフォームの例 (ただし、日本語NGです。。。使えない。)

https://tcpdf.org/examples/example_014/

No.1393
05/14 10:07

edit