跳轉到

文件生命週期

NextPDF 採用三層文件生命週期架構,將跨文件共享資源與單一文件狀態明確分離。理解此架構是正確使用 NextPDF 的基礎。


PHP Compatibility

This example uses PHP 8.5 syntax. If your environment runs PHP 8.1 or 7.4, use NextPDF Backport for a backward-compatible build.

Process(跨文件共享)
  └── DocumentFactory(建立者)
        └── Document(一次性使用)
              └── RenderingContext(所有可變狀態)

Process 層

Process 管理整個應用程式進程中共享的昂貴資源,包含字型登錄(FontRegistry)與影像快取(ImageRegistry)。建立一個 Process 實例後,應在整個應用程式生命週期中重複使用它。

use NextPDF\Core\Process;

// 應用程式啟動時建立一次
$process = Process::create();

// 可自訂資源限制
$process = Process::create(
    fontCacheDir: '/var/cache/nextpdf/fonts',
    imageCacheSizeMb: 128,
);

DocumentFactory 層

DocumentFactoryProcess 建立,負責套用設定並初始化每份文件的基礎結構。Factory 本身是無狀態的——可在多執行緒環境中共享。

use NextPDF\Core\Configuration;
use NextPDF\ValueObjects\PageSize;

$factory = $process->factory();

$document = $factory->create(
    Configuration::create(
        pageSize: PageSize::A4,
        title: 'Invoice #2026-001',
    )
);

Document 層

Document 是一次性使用的文件建構物件。建構完成後呼叫 finalize() 輸出 PDF 位元組串流,之後物件不可再使用。

use NextPDF\Core\Document;
use NextPDF\Content\TextRenderer;
use NextPDF\ValueObjects\Position;

$document->addPage();

$document->text()->write(
    text: 'Hello, NextPDF!',
    position: Position::at(x: 20.0, y: 50.0),
);

$pdfBytes = $document->finalize();

RenderingContext

RenderingContext 儲存所有每文件的可變狀態,使用 PHP 8.5 的 public private(set) 屬性確保外部唯讀、內部可寫。


PHP Compatibility

This example uses PHP 8.5 syntax. If your environment runs PHP 8.1 or 7.4, use NextPDF Backport for a backward-compatible build.

// RenderingContext 的核心屬性(外部唯讀)
final class RenderingContext
{
    public private(set) int $currentPageNumber = 0;
    public private(set) PageSize $currentPageSize;
    public private(set) FontState $fontState;
    public private(set) GraphicsState $graphicsState;
    // ...
}

獨立模式(Standalone)

對於 Workers 與無狀態環境,可跳過 Process 層直接建立文件:

use NextPDF\Core\Document;

$document = Document::createStandalone(
    Configuration::create(pageSize: PageSize::Letter)
);

每次呼叫都會建立獨立的字型與影像快取,適合短命的請求週期。

生命週期事件

Document 在各個階段會觸發事件,供進階使用者掛載自訂邏輯:

use NextPDF\Contracts\DocumentEventInterface;

$document->on(DocumentEventInterface::PAGE_ADDED, function (PageAddedEvent $event): void {
    // 例如:自動加入頁首
});

參見