LoginSignup
1
1

More than 3 years have passed since last update.

PHPWord+TCPDFでWord→PDF変換

Last updated at Posted at 2019-11-09

PHPWordを使ってWordファイルを作成していたところ、PDFファイルが欲しいという要望があり、WordからPDFの出力を試しました。変換方法はすぐに記事が見つかりましたが、日本語フォントの設定方法が意外と見つからなかったので合わせて紹介します。

環境
Windows 10
PHP 7.3.10

ライブラリのインストール

composer require tecnickcom/tcpdf
composer require phpoffice/phpword

フォントのダウンロード(必要な人のみ)

TCPDFではいくつか日本語の標準フォントが用意されています。以下参考
http://www.t-net.ne.jp/~cyfis/tcpdf/tcpdf/SetFont.html

標準以外のフォントを使用したい場合は、別途用意する必要があります。
IPAフォントダウンロードページ
https://ipafont.ipa.go.jp/old/ipafont/download.html

実装

PDF出力に関連する箇所のみ記載しています。

$phpWord = new /PhpOffice/PhpWord/PhpWord();
$template_processor = $phpWord->loadTemplate('template/sample_word.docx');
$word_file_name ='template/template.docx';
$template_processor->saveAs($word_file_name);

Settings::setPdfRendererName(Settings::PDF_RENDERER_TCPDF);
Settings::setPdfRendererPath('../vendor/tecnickcom/tcpdf');

$loadWord = IOFactory::load($word_file_name, 'Word2007');
$pdfWriter = IOFactory::createWriter($loadWord, 'PDF');
// $pdfWriter->SetFont('kozminproregular', '', 12); // 標準の日本語フォントを使う場合はこれでOK
//使用するフォントを指定
$font = new TCPDF_FONTS();
$ipagFont = $font->addTTFfont('../vendor/tecnickcom/tcpdf/fonts/ipag.ttf'); //フォントは別途用意
$pdfWriter->SetFont($ipagFont, '', 12);
//PDFファイルを保存
$pdf_file_name = 'pdf/convert_pdf.pdf';
$pdfWriter->save($pdf_file_name);

Word→PDF変換できるのは文字や表のみで、画像が入る場合、正しく変換されず画像無しのファイルとなってしまうようです。

参考

標準日本語フォントの一覧
http://www.t-net.ne.jp/~cyfis/tcpdf/tcpdf/SetFont.html

TCPDFの仕様(バグ?)で半角スペースが入っていると改行されてしまう時がある問題の解決方法
https://nakatsuyasuhiro.hatenadiary.org/entry/20100401/p1

1
1
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
1
1