萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 生成 PDF 實戰:FPDF 庫完整教學與獎牌統計報表範例

FPDF 簡介

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';
?>

核心 API 速查

方法用途關鍵參數
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()輸出 PDFdest('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 核心**不內建中文字體**,必須:

  1. 下載支援中文的 TrueType 字體(如 Noto Sans TC、思源黑體、DejaVu Sans)
  2. 使用 AddFont() 註冊(第 4 參數 `true` 表示嵌入字體子集,減小檔案)
  3. 字體檔放置於專案目錄(如 `/fonts/`),部署時一併上傳
<?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、複雜排版
DompdfHTML/CSS 轉 PDF、支援 Flex/Grid記憶體佔用大、CSS 支援不全、慢現有 HTML 模板直接轉 PDF
wkhtmltopdf完美 WebKit 渲染、支援現代 CSS/JS需安裝二進制、非純 PHP、安全風險高保真網頁轉 PDF、發票、合約
PhpSpreadsheetExcel 專業、可另存為 PDF主要為試算表、PDF 功能受限Excel 報表需同時輸出 PDF

總結

FPDF 以**零依賴、高效能、精確控制**著稱,適合生成結構化報表、發票、標籤、證書。核心成功要素:

  1. 正確**註冊 Unicode 字體**解決中文顯示
  2. 善用 **Cell/MultiCell/Image/SetXY** 精確佈局
  3. 繼承 FPDF 封裝**業務邏輯方法**(如 `addMedalRow()`)提升可維護性
  4. 大量資料使用 **流式輸出**(`Output('S')` 回傳字串分塊發送)
copyright © 萬盛學電腦網 all rights reserved