首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 使用 FPDF 產生 PDF 實戰教學

     編輯:PHP 綜合知識

FPDF 簡介

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)

中文字體處理 (重要)

  1. 下載開源字體 (如 Noto Sans TC, GenJyuuGothic)。
  2. 使用 FPDF 附帶的 makefont.php 或 fontforge 轉換為 .php + .z 檔案。
  3. 將字體檔放入 font/ 目錄,AddFont('MyFont', '', 'MyFont.php') 載入。
  4. 或改用 TCPDF / Dompdf 內建支援 UTF-8 TTF,免轉換步驟。

常見問題

  • 中文亂碼:未載入 UTF-8 字體或字體無對應字型。
  • 圖片不顯示:路徑錯誤、格式不支援 (需 JPG/PNG/GIF)、檔案權限。
  • 記憶體不足:大量圖片/資料時調整 memory_limit 或分批產生。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved