pdfを出力する時に、全てをhtmlで書いてもいいのですが、ロゴなどはpdfテンプレートで使い回すという方法も便利なので紹介します。
composer require setasign/fpdi
composer require tecnickcom/tcpdf
composer require wyrihaximus/html-compress
格納場所 resources/pdf を作成します。
mkdir resources/pdf
ここに pdf と html をコピーします。以下のファイル名とします。
template_01.pdf
template_01.pdf.html
http://jikasei.me/font/genshin/
明朝フォントはこちらの 源様明朝 がお勧めです。
https://github.com/ButTaiwan/genyo-font
格納場所 resources/fonts を作成します。
mkdir resources/fonts
ここに 拡張子が .ttf のフォントファイルをコピーします。
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");
}
このサイトがとても便利です
htmlをminifyしましょう
composer require wyrihaximus/html-compress
$parser = \WyriHaximus\HtmlCompress\Factory::construct();
$html = $parser->compress($html);
以下の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>