LoginSignup
3
9

More than 3 years have passed since last update.

PHPでPDFを出力する

Posted at

今回使うライブラリは、既存のPDF文書をテンプレートとして引用できるので、静的なレイアウト作成や細かい調整などはwordやExcelで行うことができます。
動的なデータに関しては、座標指定で配置可能です:grinning:

ライブラリとフォントをダウンロードする

  • TCPDF
    PDFを作成して書き込みができるライブラリ
  • FPDI
    既存のPDFを読み込めるライブラリ
  • 明朝フォント

それぞれ解凍して、任意の場所に配置してください。
(あとでパスを指定すればいいのでどこでもOK)

実際のコード

<?php

// 文字コードをUTF-8に
mb_internal_encoding("UTF-8");

// クラスをインポート
use setasign\Fpdi\TcpdfFpdi;

// TCPDFの読み込み
require_once('./TCPDF/tcpdf.php');
// FPDIの読み込み
require_once('./FPDI/src/autoload.php');

/*
IPA Font (IPA Fonts 4 fonts package)   IPAfont00303.zip
|--Readme   Readme_IPAfont00303.txt
|--IPA Font License Agreement v1.0   IPA_Font_License_Agreement_v1.0.txt
|--IPAGothic   ipag.ttf
|--IPAPGothic   ipagp.ttf
|--IPAMincho   ipam.ttf
|--IPAPMincho   ipamp.ttf
*/

// フォントの読み込み
$font_path = './TCPDF/fonts/ipam.ttf';

// フォントを適用
$font = new TCPDF_FONTS();
$fontR = $font->addTTFfont($font_path);

// PDFの読み込み
$base_pdf = './PDF/sample.pdf';

// 出力するPDFの初期設定
$pdf = new TcpdfFpdi('L', 'mm', 'A4');
$pdf->setPrintHeader( false );
$pdf->setPrintFooter( false );

// テンプレートPDFの読み込み
$pdf->setSourceFile($base_pdf);

//以下PDF---------------------------------------------------------------
//1ページ目--------------------------------------------------------------
$pdf->AddPage('P', 'A4');
$pdf->useTemplate($pdf->importPage(1));

$pdf->SetFont($fontR , '', 9,'',true);
$pdf->Text( 170 , 28  ,"Test");

//2ページ目--------------------------------------------------------------
$pdf->AddPage('P', 'A4');
$pdf->useTemplate($pdf->importPage(2));


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