LoginSignup
9
14

More than 5 years have passed since last update.

LaravelでテンプレートPDFを出力する

Posted at

PHPでPDF化の実装パターン

  1. HTMLからPDFにする
  2. テンプレートとなるPDFに文字を出力する

今回は2の話。

実装

TCPDFとFPDIを組み合わせて実装
composer require tecnickcom/tcpdf
composer require setasign/fpdi

これで使えるようになった。

以下は実際に使用した設定内容。

controller.php
public function generatePdf()
    {
        /*
         * PDFの初期設定
         */
        $pdf = new Fpdi('L', 'mm', 'A4');

        // テンプレートPDFの設定
        $template_path = public_path('assets/pdfs/template.pdf');
        $pdf->setSourceFile($template_path);

        $pdf->setPrintHeader(false);
        $pdf->setPrintFooter(false);
        $pdf->SetAutoPageBreak(false);
        $pdf->SetAutoPageBreak(false);
        $pdf->SetMargins(0, 0, 0);
        $pdf->addPage();

        $font = new TCPDF_FONTS();

        //フォントの設定
        $font_bold = $font->addTTFfont(storage_path('fonts/ipag.ufm'));
        $pdf->setFont($font_bold, '', 30);

        $page = $pdf->importPage(1);
        $pdf->useTemplate($page);

        /*
         * PDFに表示するデータ
         */
        //ID
        $pdf->SetXY(100, 49);
        $pdf->Write(0, '1'));

        //名前
        $pdf->SetXY(100, 61);
        $pdf->Write(1, 'やまだたろう');


        $pdf->output();

        return Redirect::back();
    }

1個だけ詰まった点は、SetMarginsを設定しているのに余白の調整が上手くいかない。

そもそもA4サイズ(210 × 297)で作成されていないんじゃないのかと思って変換したら、ビンゴ!

当たり前だが、HTMLのようにレイアウトの調整は出来ないからPDF側で正確に調整してもらう必要がある。

HTMLからPDFにする際はレイアウトの制限が多くて、手間だったがテンプレートがある方は文字の出力位置に手間取るぐらいでわかってしまえばサクッと実装できるのがいいね。

9
14
1

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
9
14