跳轉到

快速開始:5 分鐘產生第一份 PDF

本指南帶你以最少的程式碼產生一份可用的 PDF 文件,涵蓋文字排版、圖像嵌入與檔案輸出。

前置條件:請確認已完成 安裝指南 中的 Core 套件安裝。


Backport 相容性說明

PHP 8.5 語法需求:本頁所有範例使用 PHP 8.5 語法,包含 public private(set) 屬性、命名引數(named arguments)等特性。

若你的環境為 PHP 8.1PHP 7.4,請改用 nextpdf/backport 套件。 API 介面完全相同,Backport 套件透過 Rector 自動降版處理語法差異。 詳見 PHP 相容性說明


步驟一:安裝套件

composer require nextpdf/core

步驟二:最小可運行範例

建立 generate.php

<?php

declare(strict_types=1);

use NextPDF\Core\Document;

// 建立獨立文件實例(CLI / 腳本環境)
$doc = Document::createStandalone();

// 新增第一頁(預設 A4 直向)
$doc->addPage();

// 新增文字
$doc->text('Hello, NextPDF!', x: 20, y: 30);

// 儲存至檔案
$doc->save('/tmp/hello.pdf');

echo 'PDF 已生成:/tmp/hello.pdf' . PHP_EOL;

執行:

php generate.php

成功後,/tmp/hello.pdf 將包含一頁印有 "Hello, NextPDF!" 的 A4 文件。


步驟三:加入更多內容

以下範例展示更完整的文件結構,包含頁面設定、字型、圖像與多段文字:

<?php

declare(strict_types=1);

use NextPDF\Core\Document;
use NextPDF\Core\ValueObjects\PageSize;
use NextPDF\Core\ValueObjects\Color;
use NextPDF\Core\ValueObjects\FontSize;
use NextPDF\Core\Typography\FontWeight;

$doc = Document::createStandalone();

// 設定文件中繼資料
$doc->setMetadata(
    title: 'NextPDF 範例文件',
    author: 'Your Name',
    subject: 'PDF 快速開始',
    creator: 'nextpdf/core',
);

// 新增第一頁(A4 直向)
$doc->addPage(size: PageSize::A4);

// 設定字型(Core 內建 Noto Sans 多語系字型)
$doc->setFont(family: 'NotoSans', size: FontSize::of(24), weight: FontWeight::Bold);
$doc->setColor(Color::fromHex('#1E3A8A'));

// 標題
$doc->text('NextPDF 快速開始範例', x: 20, y: 30);

// 正文字型
$doc->setFont(family: 'NotoSans', size: FontSize::of(12), weight: FontWeight::Regular);
$doc->setColor(Color::fromHex('#374151'));

// 多行文字
$doc->multilineText(
    text: '這是使用 NextPDF Core 生成的 PDF 文件。\n支援 Unicode、CJK 文字與自動換行。',
    x: 20,
    y: 60,
    maxWidth: 170,
    lineHeight: 6,
);

// 水平分隔線
$doc->line(x1: 20, y1: 80, x2: 190, y2: 80, color: Color::fromHex('#E5E7EB'));

// 嵌入圖像(支援 JPEG、PNG、WebP、SVG)
// $doc->image('/path/to/logo.png', x: 20, y: 90, width: 50);

// 新增第二頁
$doc->addPage(size: PageSize::A4);
$doc->setFont(family: 'NotoSans', size: FontSize::of(16), weight: FontWeight::SemiBold);
$doc->text('第二頁', x: 20, y: 30);

// 儲存至檔案
$doc->save('/tmp/nextpdf-example.pdf');

// 或輸出為字串(用於 HTTP Response)
// $pdfString = $doc->output();

echo '文件已生成:/tmp/nextpdf-example.pdf' . PHP_EOL;

步驟四:HTTP 回應輸出

在 Web 環境中,通常需要將 PDF 直接回傳給瀏覽器:

<?php

declare(strict_types=1);

use NextPDF\Core\Document;

$doc = Document::createStandalone();
$doc->addPage();
$doc->text('Web PDF 範例', x: 20, y: 30);

// 取得 PDF 二進位內容
$content = $doc->output();

// 設定 HTTP 標頭並輸出
header('Content-Type: application/pdf');
header('Content-Disposition: inline; filename="document.pdf"');
header('Content-Length: ' . strlen($content));

echo $content;
exit;

框架整合:若使用 Laravel、Symfony 或 CodeIgniter,請使用對應的框架整合套件, 它們提供更完善的 Response 物件封裝: - Laravel 快速開始 - Symfony 快速開始 - CodeIgniter 快速開始


步驟五:嵌入圖像

<?php

declare(strict_types=1);

use NextPDF\Core\Document;
use NextPDF\Core\ValueObjects\PageSize;

$doc = Document::createStandalone();
$doc->addPage(size: PageSize::A4);

// 從檔案路徑嵌入(JPEG / PNG / WebP / SVG)
$doc->image(
    path: '/path/to/logo.png',
    x: 20,
    y: 20,
    width: 60,   // mm(保持比例,height 可省略)
);

// 從記憶體嵌入(例如從資料庫取得的 BLOB)
// $doc->imageFromString(data: $binaryData, mimeType: 'image/png', x: 20, y: 90, width: 60);

$doc->save('/tmp/with-image.pdf');

Document::createStandalone() 說明

Document::createStandalone() 是 CLI 腳本與測試環境的主要入口點。它會在單一呼叫中 初始化完整的 FontRegistryImageRegistryRenderingContext

// 函式簽章
public static function createStandalone(
    ?ProcessConfig $config = null,
): Document
參數 類型 說明
$config ?ProcessConfig 字型目錄、快取路徑、Spectrum 連線設定等全域配置

在框架環境(Laravel、Symfony)中,請改用 DocumentFactory(透過 DI Container 注入), 它支援跨 Request 的 Registry 共享,避免重複載入字型。


常見問題

Q:產生的 PDF 無法顯示中文?

Core 內建 Noto Sans CJK 字型子集,但需要明確設定字型家族:

$doc->setFont(family: 'NotoSansCJKtc'); // 繁體中文
// 或
$doc->setFont(family: 'NotoSansCJKsc'); // 簡體中文

Q:如何設定頁面邊距?

$doc->addPage(size: PageSize::A4);
$doc->setMargins(top: 20, right: 15, bottom: 20, left: 15); // 單位:mm

Q:save() 需要哪些目錄權限?

目標目錄必須對 PHP 程序具有寫入權限。建議使用絕對路徑並在生產環境中預先建立目錄:

$outputDir = '/var/www/storage/pdfs';
if (!is_dir($outputDir)) {
    mkdir($outputDir, 0755, recursive: true);
}
$doc->save($outputDir . '/document.pdf');

下一步