跳轉到

PDF 生成指南

先決條件

composer require nextpdf/core

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.

文件生命週期

獨立模式(CLI / 一次性使用)

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

$document = Document::createStandalone(
    pageSize: PageSize::A4,
    margin: Margin::symmetric(vertical: 20.0, horizontal: 25.0),
);

Worker 模式(長執行程序 / Octane)

use NextPDF\Core\DocumentFactory;
use NextPDF\Core\Support\FontRegistry;
use NextPDF\Core\Support\ImageRegistry;

// 在程序啟動時初始化一次(昂貴操作)
$fontRegistry  = FontRegistry::create()->registerDirectory('/fonts');
$imageRegistry = ImageRegistry::create();

$factory = DocumentFactory::create(
    fontRegistry:  $fontRegistry,
    imageRegistry: $imageRegistry,
);

// 每個請求建立新的 Document(廉價操作)
$document = $factory->make(pageSize: PageSize::A4);

頁面管理

$page = $document->pages()->add(size: PageSize::A4);
$document->pages()->add(size: PageSize::A3->landscape());

文字渲染

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

$renderer = $document->text();
$renderer->write(
    text:     'Hello, World!',
    position: Position::at(x: 25.0, y: 50.0),
    fontSize: 14.0,
    fontName: 'NotoSans',
);

圖形繪製

$drawing = $document->drawing();
$drawing->rectangle(
    x:      25.0,
    y:      100.0,
    width:  160.0,
    height: 80.0,
    fill:   '#1E3A8A',
);

圖像嵌入

$image = $document->images()->embed('/path/to/logo.png');
$document->drawing()->image(
    image:  $image,
    x:      25.0,
    y:      20.0,
    width:  50.0,
);

輸出

// 儲存至檔案
$document->save('/output/document.pdf');

// 取得位元組字串
$bytes = $document->toString();

// 串流輸出(適用 HTTP 回應)
$document->stream(filename: 'document.pdf', inline: true);

進階主題