FPDF 是純 PHP 實現的 PDF 生成庫,**無需安裝擴展**,支援:頁面設定、頁首頁尾、自動分頁/換行、文字對齊、圖片(JPEG/PNG)、TrueType/Type1 字型、UTF-8(需字體檔)、資料表格、圖層、加密等。
官網:https://www.fpdf.org/ | GitHub:Setasign/FPDF
<?php
// 方式 1:Composer(推薦)
// composer require setasign/fpdf
// 方式 2:手動下載解壓至專案目錄
require_once __DIR__ . '/fpdf/fpdf.php';
?>
| 方法 | 用途 | 關鍵參數 |
|---|---|---|
| AddPage() | 新增頁面 | orientation('P'/'L'), size('A4'/'Letter'/array) |
| SetFont() | 設定字體 | family, style('B/I/U'), size(pt) |
| Cell() | 儲存格(文字+邊框+背景) | w, h, txt, border, ln, align, fill, link |
| MultiCell() | 多行文字(自動換行) | w, h, txt, border, align, fill |
| Image() | 插入圖片 | file, x, y, w, h, type, link |
| Ln() | 換行 | h (預設當前字體高度) |
| SetX() / SetY() | 設定當前 X/Y 座標 | 座標值 |
| SetTextColor() | 設定文字顏色 | R, G, B (0-255) |
| SetFillColor() | 設定填充顏色 | R, G, B |
| Output() | 輸出 PDF | dest('I'輸出瀏覽器/'D'下載/'F'存檔/'S'字串), name |
<?php
require_once __DIR__ . '/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],
['country' => '英國', 'flag' => 'flags/gb.png', 'gold' => 22, 'silver' => 21, 'bronze' => 22],
['country' => '俄羅斯', 'flag' => 'flags/ru.png', 'gold' => 20, 'silver' => 28, 'bronze' => 23],
];
// 2. 擴充 FPDF 類別
class MedalPDF extends FPDF {
private $colWidths = [30, 20, 25, 25, 25]; // 國旗、國家、金、銀、銅
private $headers = ['', '國家', '金牌', '銀牌', '銅牌'];
public function Header() {
$this->SetFont('DejaVu', 'B', 18);
$this->Cell(0, 15, '2024 夏季奧運獎牌榜', 0, 1, 'C');
$this->Ln(5);
// 表頭
$this->SetFont('DejaVu', 'B', 11);
$this->SetFillColor(68, 114, 196); // 深藍
$this->SetTextColor(255, 255, 255);
foreach ($this->headers as $i => $header) {
$this->Cell($this->colWidths[$i], 10, $header, 1, 0, 'C', true);
}
$this->Ln();
$this->SetTextColor(0, 0, 0); // 恢復黑色
}
public function Footer() {
$this->SetY(-15);
$this->SetFont('DejaVu', 'I', 8);
$this->Cell(0, 10, '第 ' . $this->PageNo() . ' 頁 / 共 {nb} 頁', 0, 0, 'C');
}
// 自訂方法:新增一行獎牌資料
public function addMedalRow(array $row): void {
// 計算行高(取圖片高與字體高的最大值)
$rowHeight = 18;
// 檢查是否需要分頁
if ($this->GetY() + $rowHeight > $this->h - $this->bMargin) {
$this->AddPage();
}
$x = $this->GetX();
$y = $this->GetY();
// 國旗圖片(置中於第一欄)
if (file_exists($row['flag'])) {
$imgW = 16;
$imgX = $x + ($this->colWidths[0] - $imgW) / 2;
$imgY = $y + ($rowHeight - 12) / 2;
$this->Image($row['flag'], $imgX, $imgY, $imgW);
}
// 國家名(第 2 欄)
$this->SetXY($x + $this->colWidths[0], $y);
$this->SetFont('DejaVu', '', 10);
$this->Cell($this->colWidths[1], $rowHeight, $row['country'], 1, 0, 'C');
// 獎牌數(第 3-5 欄)
$this->SetFont('DejaVu', 'B', 12);
// 金牌 - 金色
$this->SetTextColor(200, 160, 12);
$this->Cell($this->colWidths[2], $rowHeight, (string)$row['gold'], 1, 0, 'C');
// 銀牌 - 銀色
$this->SetTextColor(170, 170, 170);
$this->Cell($this->colWidths[3], $rowHeight, (string)$row['silver'], 1, 0, 'C');
// 銅牌 - 銅色
$this->SetTextColor(187, 120, 68);
$this->Cell($this->colWidths[4], $rowHeight, (string)$row['bronze'], 1, 0, 'C');
$this->Ln($rowHeight);
$this->SetTextColor(0, 0, 0); // 恢復
}
// 總計行
public function addTotalRow(array $totals): void {
$this->SetFont('DejaVu', 'B', 11);
$this->SetFillColor(230, 230, 230);
$this->Cell(array_sum($this->colWidths), 10, '總計', 1, 0, 'R', true);
$this->SetTextColor(200, 160, 12);
$this->Cell($this->colWidths[2], 10, (string)$totals['gold'], 1, 0, 'C', true);
$this->SetTextColor(170, 170, 170);
$this->Cell($this->colWidths[3], 10, (string)$totals['silver'], 1, 0, 'C', true);
$this->SetTextColor(187, 120, 68);
$this->Cell($this->colWidths[4], 10, (string)$totals['bronze'], 1, 0, 'C', true);
$this->Ln();
}
}
// 3. 字體註冊(支援中文必須)
$pdf = new MedalPDF('P', 'mm', 'A4');
$pdf->AliasNbPages(); // 啟用 {nb} 總頁數佔位符
// 註冊支援 Unicode 的字體(需下載 DejaVu Sans 字體檔)
$fontDir = __DIR__ . '/fonts/';
$pdf->AddFont('DejaVu', '', $fontDir . 'DejaVuSansCondensed.ttf', true);
$pdf->AddFont('DejaVu', 'B', $fontDir . 'DejaVuSansCondensed-Bold.ttf', true);
$pdf->AddFont('DejaVu', 'I', $fontDir . 'DejaVuSansCondensed-Oblique.ttf', true);
$pdf->AddFont('DejaVu', 'BI', $fontDir . 'DejaVuSansCondensed-BoldOblique.ttf', true);
// 4. 生成內容
$pdf->AddPage();
$totals = ['gold' => 0, 'silver' => 0, 'bronze' => 0];
foreach ($medals as $row) {
$pdf->addMedalRow($row);
$totals['gold'] += $row['gold'];
$totals['silver'] += $row['silver'];
$totals['bronze'] += $row['bronze'];
}
$pdf->addTotalRow($totals);
// 5. 輸出
$pdf->Output('D', 'olympic_medals_' . date('Ymd') . '.pdf'); // D=強制下載
?>
FPDF 核心**不內建中文字體**,必須:
AddFont() 註冊(第 4 參數 `true` 表示嵌入字體子集,減小檔案)<?php
// 註冊 Noto Sans TC(繁體中文)
$pdf->AddFont('NotoSansTC', '', '/fonts/NotoSansTC-Regular.ttf', true);
$pdf->AddFont('NotoSansTC', 'B', '/fonts/NotoSansTC-Bold.ttf', true);
$pdf->SetFont('NotoSansTC', '', 12);
// 現在可正常輸出中文
$pdf->Cell(0, 10, '中文測試:你好世界', 0, 1);
?>
| 問題 | 原因 | 解決 |
|---|---|---|
| 中文顯示方塊/亂碼 | 未註冊 Unicode 字體 | AddFont() 註冊 TTF 字體,SetFont 使用該字體家族 |
| 檔案過大 | 完整嵌入字體檔 | AddFont 第 4 參數 true(子集嵌入)、刪除無用字形 |
| 自動分頁位置錯誤 | SetAutoPageBreak 邊距設定 | $pdf->SetAutoPageBreak(true, 20); // 底部 20mm |
| 表格跨頁斷裂 | Cell 無法跨頁 | 用 MultiCell 或手動檢查 GetY() 觸發 AddPage() |
| 圖片不顯示 | 路徑錯誤/格式不支援 | 使用絕對路徑、確認 JPEG/PNG、檢查檔案權限 |
| 庫 | 優點 | 缺點 | 適用場景 |
|---|---|---|---|
| FPDF | 零依賴、輕量、純 PHP、成熟穩定 | 無 HTML/CSS 支援、複雜排版代碼量大 | 簡單報表、標籤、證書、資料表 |
| TCPDF | 功能豐富、支援 HTML、條碼、簽章 | 體積大、效能較慢、API 複雜 | 需 HTML 轉 PDF、複雜排版 |
| Dompdf | HTML/CSS 轉 PDF、支援 Flex/Grid | 記憶體佔用大、CSS 支援不全、慢 | 現有 HTML 模板直接轉 PDF |
| wkhtmltopdf | 完美 WebKit 渲染、支援現代 CSS/JS | 需安裝二進制、非純 PHP、安全風險 | 高保真網頁轉 PDF、發票、合約 |
| PhpSpreadsheet | Excel 專業、可另存為 PDF | 主要為試算表、PDF 功能受限 | Excel 報表需同時輸出 PDF |
FPDF 以**零依賴、高效能、精確控制**著稱,適合生成結構化報表、發票、標籤、證書。核心成功要素: