PHP 擁有強大的擴充生態,PDFLib 讓開發者能直接在 PHP 中動態產生專業級 PDF 文件。本文從安裝設定、基礎繪圖、文字排版、圖片嵌入、幾何繪圖到文件屬性設定,完整涵蓋 PDF 產生的核心技術。
pecl install pdflibphp_pdf.dll 放入 ext/,於 php.ini 啟用 extension=php_pdf.dll$pdf = PDF_new();PDF_open_file($pdf, 'output.pdf');PDF_close($pdf);<?php
$pdf = PDF_new();
PDF_open_file($pdf, 'report.pdf');
PDF_begin_page($pdf, 595, 842); // A4: 595x842 pt
// 字體設定
$font = PDF_findfont($pdf, 'Helvetica', 'host', 1);
PDF_setfont($pdf, $font, 12);
// 標題
PDF_show_xy($pdf, 'Monthly Sales Report', 50, 780);
// 繪製分隔線
PDF_setcolor($pdf, 'stroke', 'rgb', 0, 0, 0);
PDF_moveto($pdf, 50, 770);
PDF_lineto($pdf, 545, 770);
PDF_stroke($pdf);
// 表格標頭
$y = 740;
$headers = ['Product', 'Qty', 'Unit Price', 'Total'];
$xPos = [50, 250, 350, 450];
PDF_setfont($pdf, $font, 10);
foreach ($headers as $i => $h) {
PDF_show_xy($pdf, $h, $xPos[$i], $y);
}
// 表格資料(示範)
$data = [
['Widget A', 100, 12.50, 1250.00],
['Widget B', 50, 25.00, 1250.00],
['Gadget C', 200, 8.75, 1750.00],
];
$y -= 20;
foreach ($data as $row) {
foreach ($row as $i => $val) {
PDF_show_xy($pdf, is_numeric($val) ? number_format($val,2) : $val, $xPos[$i], $y);
}
$y -= 18;
}
// 嵌入圖片(Logo)
$img = PDF_open_image_file($pdf, 'jpeg', 'logo.jpg');
PDF_place_image($pdf, $img, 50, 785, 0.5);
// 繪製矩形與圓形
PDF_setcolor($pdf, 'fill', 'rgb', 1, 1, 0); // 黃填滿
PDF_setcolor($pdf, 'stroke', 'rgb', 0, 0, 0); // 黑邊框
PDF_rect($pdf, 50, 500, 200, 100);
PDF_fill_stroke($pdf);
PDF_setcolor($pdf, 'fill', 'rgb', 0, 1, 0); // 綠填滿
PDF_setcolor($pdf, 'stroke', 'rgb', 0, 0, 1); // 藍邊框
PDF_circle($pdf, 400, 550, 50);
PDF_fill_stroke($pdf);
// 文件資訊
PDF_set_info_author($pdf, 'Sales Dept');
PDF_set_info_title($pdf, 'Monthly Report');
PDF_set_info_subject($pdf, 'PHP PDFLib Demo');
PDF_set_info_keywords($pdf, 'PHP, PDF, PDFLib, Report');
PDF_end_page($pdf);
PDF_close($pdf);
echo 'PDF generated: report.pdf';
?>
| 功能 | 函式 | 說明 |
|---|---|---|
| 新頁面 | PDF_begin_page($pdf, $w, $h) | 單位為 point (1/72 inch),A4=595x842 |
| 字體載入 | PDF_findfont($pdf, $name, $enc, $embed) | 回傳字體物件,$embed=1 內嵌字體 |
| 設定字體 | PDF_setfont($pdf, $font, $size) | |
| 指定座標寫文字 | PDF_show_xy($pdf, $text, $x, $y) | 原點(0,0)在左下角 |
| 顏色設定 | PDF_setcolor($pdf, $type, $model, $c1, $c2, $c3) | type: stroke/fill/both;model: rgb/cmyk;值 0~1 |
| 直線 | PDF_moveto/lineto/stroke | 移動筆觸→定義終點→描繪 |
| 矩形 | PDF_rect($pdf, $x, $y, $w, $h) | 左下角座標+寬高 |
| 圓形 | PDF_circle($pdf, $cx, $cy, $r) | 圓心座標+半徑 |
| 填滿並描邊 | PDF_fill_stroke($pdf) | 同時套用 fill 與 stroke 顏色 |
| 圖片嵌入 | PDF_open_image_file/PDF_place_image | 支援 JPEG, PNG, TIFF, GIF;最後參數為縮放比例 |
PDF_findfont($pdf, 'MSung-Light', 'UniCNS-UCS2-H', 1) 載入memory_limit,或分批產生再合併PDF_findfont