跳轉到

頁首與頁尾

NextPDF 的頁首頁尾系統在 finalize() 時批量渲染,確保頁碼等動態內容能正確反映最終頁數。支援奇偶頁不同頁首、首頁不顯示頁首、以及複雜的自訂頁首回調。

簡單頁首頁尾

use NextPDF\Layout\HeaderFooter;
use NextPDF\Layout\HeaderConfig;
use NextPDF\Layout\FooterConfig;

// 靜態頁首
$document->header()->set(
    config: HeaderConfig::create(
        text: 'Annual Report 2026 — Acme Corp',
        alignment: TextAlignment::Center,
        fontSize: 9.0,
        borderBottom: true,
        marginBottom: 5.0,
    ),
);

// 頁碼頁尾
$document->footer()->set(
    config: FooterConfig::create(
        text: 'Page {page} of {total}',   // 佔位符語法
        alignment: TextAlignment::Center,
        fontSize: 9.0,
        borderTop: true,
    ),
);

自訂頁首回調

// 使用回調函數渲染複雜頁首
$document->header()->setCallback(
    callback: function (HeaderContext $ctx): void {
        $draw = $ctx->draw();
        $text = $ctx->text();
        $pageNumber = $ctx->getPageNumber();
        $totalPages = $ctx->getTotalPages();

        // 左側:公司 Logo
        $ctx->images()->place(
            path: '/path/to/logo.png',
            position: Rectangle::fromXY(x: 0.0, y: 0.0, width: 30.0, height: 12.0),
        );

        // 右側:頁碼
        $text->write(
            text: "Page {$pageNumber} / {$totalPages}",
            position: Position::at(x: 140.0, y: 4.0),
            style: FontStyle::create(fontSize: 9.0),
        );

        // 底部分隔線
        $draw->line(
            from: Position::at(x: 0.0, y: 14.0),
            to: Position::at(x: 170.0, y: 14.0),
            stroke: StrokeStyle::solid(color: [30, 58, 138], width: 0.5),
        );
    },
);

奇偶頁設定

// 奇數頁(右頁):右對齊頁碼
$document->header()->setOdd(
    config: HeaderConfig::create(
        text: 'Annual Report 2026',
        alignment: TextAlignment::Left,
    ),
);

// 偶數頁(左頁):左對齊頁碼
$document->header()->setEven(
    config: HeaderConfig::create(
        text: '{page}',
        alignment: TextAlignment::Right,
    ),
);

首頁設定

// 首頁不顯示頁首(封面頁)
$document->header()->skipFirstPage();

// 或設定首頁專用頁首
$document->header()->setFirstPage(
    config: HeaderConfig::create(
        text: 'CONFIDENTIAL',
        alignment: TextAlignment::Center,
        fontSize: 8.0,
        color: Color::rgb(200, 50, 50),
    ),
);

頁碼格式

use NextPDF\Layout\PageNumberFormat;

// 羅馬數字頁碼(用於前言)
$document->footer()->set(
    config: FooterConfig::create(
        text: '{page}',
        pageNumberFormat: PageNumberFormat::LowerRoman,  // i, ii, iii...
    ),
);

參見