FPDF 是純 PHP 實作的 PDF 產生類別,**不需安裝 PDFlib 擴充套件**,支援 UTF-8 (需字體)、圖片、自動換頁、頁首頁尾、表格繪製等功能,適合報表、發票、證書產生。
# 官網下載或 Composer
composer require setasign/fpdf
# 或手動下載 fpdf.php 放入專案
require_once 'fpdf/fpdf.php';
<?php
require_once 'fpdf/fpdf.php';
// 1. 資料來源
$medals = [
['country' => '中國', 'flag' => 'flags/cn.png', 'gold' => 38, 'silver' => 32, 'bronze' => 18],
['country' => '美國', 'flag' => 'flags/us.png', 'gold' => 39, 'silver' => 41, 'bronze' => 33],
['country' => '日本', 'flag' => 'flags/jp.png', 'gold' => 27, 'silver' => 14, 'bronze' => 17],
];
// 2. 繼承 FPDF 自訂頁首/列印邏輯
class MedalPDF extends FPDF {
public function header() {
$this->SetFont('NotoSansTC', 'B', 20);
$this->Cell(0, 15, '奧運獎牌統計表', 0, 1, 'C');
$this->Ln(5);
}
public function footer() {
$this->SetY(-15);
$this->SetFont('NotoSansTC', '', 10);
$this->Cell(0, 10, '第 ' . $this->PageNo() . ' 頁', 0, 0, 'C');
}
public function addCountryRow($country, $flagPath, $gold, $silver, $bronze) {
$this->SetFont('NotoSansTC', '', 14);
$this->Image($flagPath, $this->GetX(), $this->GetY(), 10); // 國旗 10mm
$this->Cell(30, 10, $country, 1, 0, 'C');
$this->SetTextColor(200, 160, 12); // 金色
$this->Cell(25, 10, (string)$gold, 1, 0, 'C');
$this->SetTextColor(170, 170, 170); // 銀色
$this->Cell(25, 10, (string)$silver, 1, 0, 'C');
$this->SetTextColor(187, 120, 68); // 銅色
$this->Cell(25, 10, (string)$bronze, 1, 1, 'C');
$this->SetTextColor(0, 0, 0); // 恢復黑色
}
}
// 3. 產生 PDF
$pdf = new MedalPDF('P', 'mm', 'A4');
$pdf->AddFont('NotoSansTC', '', 'NotoSansTC-Regular.php'); // 需先用 makefont 轉換
$pdf->AddFont('NotoSansTC', 'B', 'NotoSansTC-Bold.php');
$pdf->AddPage();
foreach ($medals as $m) {
$pdf->addCountryRow($m['country'], $m['flag'], $m['gold'], $m['silver'], $m['bronze']);
}
$pdf->Output('D', 'medals.pdf'); // D=下載, I=瀏覽器內嵌, F=存檔
?>
| 方法 | 用途 |
|---|---|
| AddPage([orientation]) | 新增頁面 |
| SetFont(family, style, size) | 設定字體 (style: '', B, I, U) |
| Cell(w, h, txt, border, ln, align) | 繪製儲存格 (文字、框線、換行) |
| MultiCell(w, h, txt, border, align) | 多行文字自動換行 |
| Image(file, x, y, w, h, type, link) | 插入圖片 (JPG/PNG/GIF) |
| SetTextColor(r, g, b) | 設定文字顏色 (RGB) |
| SetFillColor(r, g, b) | 設定填滿顏色 |
| Ln(h) | 換行 |
| Output(dest, name) | 輸出 (D/I/F/S) |
makefont.php 或 fontforge 轉換為 .php + .z 檔案。font/ 目錄,AddFont('MyFont', '', 'MyFont.php') 載入。memory_limit 或分批產生。