Zend_Pdf
これまで日本語が扱えないので、使ってみたいけれど、使わなかったZend_Pdf。Zend Framework 1.5からUTF-8に対応したということで日本語を扱う私(我々)にとってはうれしいものです。
Zend_Pdf-ex.php (ごく簡単な例)
<?php
/**
* Zend_PdfでHello World!
*/
/** Zend_Pdfのロード */
require_once 'Zend/Pdf.php';
/** 生成 */
// Zend_Pdfのインスタンス生成
$pdf = new Zend_Pdf();
// A4サイズのページを作成
$pdf->pages[] = $pdf->newPage(Zend_Pdf_Page::SIZE_A4);
/** 設定 */
// フォントの指定(標準フォント:Helvetica)
$font = Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_HELVETICA);
// フォントを36ptで適用
$pdf->pages[0]->setFont($font, 36);
// 文字列定義
$text = 'Hello World!';
// 100pt, 700pt(左下から)の位置にUTF-8で描画
$pdf->pages[0]->drawText($text, 100, 700, 'UTF-8');
/** 出力 */
// HTTPヘッダ:PDFを出力
header('Content-type: application/pdf');
// HTTPヘッダ:ファイル名をhello_world.pdfに
header('Content-Disposition: attachment; filename="hello_world.pdf"');
// ドキュメントを出力
echo $pdf->render();
このコードを実行すると、ブラウザにヘルパープラグインが指定されていれば、ブラウザにPDFファイルが表示されます。そうでない場合、ダウンロードするかどうかのダイアログが表示されます。
Zend_Pdf-ex.phpを実行し、保存後、ビューアーで表示
一方、PDFをファイルとして保存するには、出力の部分でrender()メソッドではなく、save()メソッドにファイル名を指定して使用します(もちろん、HTTPヘッダは必要ありませんし、保存ディレクトリには書き込み権限が必要です)。
Zend_Pdf-ex2.php (ごく簡単な例、ファイルにして保存)
<?php
/**
* Zend_PdfでHello World!
*/
/** Zend_Pdfのロード */
require_once 'Zend/Pdf.php';
/** 生成 */
// Zend_Pdfのインスタンス生成
$pdf = new Zend_Pdf();
// A4サイズのページを作成
$pdf->pages[] = $pdf->newPage(Zend_Pdf_Page::SIZE_A4);
/** 設定 */
// フォントの指定(標準フォント:Helvetica)
$font = Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_HELVETICA);
// フォントを36ptで適用
$pdf->pages[0]->setFont($font, 36);
// 文字列定義
$text = 'Hello World!';
// 100pt, 700ptの位置にUTF-8で描画
$pdf->pages[0]->drawText($text, 100, 700, 'UTF-8');
/** 出力 */
// ファイル名
$fileName = 'hello.pdf';
// ドキュメントを保存
$pdf->save($fileName);
サーバサイドでPDFが生成できると、いろいろ楽しいことが出来そうです。