跳轉到

頁面區域

NextPDF 提供精確的頁面區域管理,幫助開發者在正確的位置放置內容而無需手動計算邊距偏移。PageRegion 系統將頁面分為可使用的內容區域與保留的邊距區域,並提供相對定位的輔助工具。

頁面區域定義

use NextPDF\Layout\PageRegion;

// 取得當前頁面的內容區域
$contentArea = $document->layout()->getContentArea();
// $contentArea->x, ->y(左下角在 PDF 座標系統中的位置)
// $contentArea->width, ->height(可用寬高)

// 取得完整頁面區域(含邊距)
$fullPage = $document->layout()->getPageArea();

PDF 標準頁面框

use NextPDF\Layout\PageBox;

// 設定各標準頁面框
$document->currentPage()->setMediaBox(/* 媒體框 */);
$document->currentPage()->setCropBox(/* 裁切框:閱讀器顯示範圍 */);
$document->currentPage()->setBleedBox(/* 出血框 */);
$document->currentPage()->setTrimBox(/* 裁切後尺寸 */);
$document->currentPage()->setArtBox(/* 版面設計區域 */);
頁面框 PDF 名稱 用途
MediaBox MediaBox 實體媒體尺寸(必要)
CropBox CropBox 閱讀器顯示範圍
BleedBox BleedBox 出血延伸範圍
TrimBox TrimBox 裁切後的最終尺寸
ArtBox ArtBox 版面有意義的內容範圍

相對定位輔助

use NextPDF\Layout\Anchor;

// 相對於內容區域的位置(不需手動加邊距偏移)
$document->text()->write(
    text: 'Top-left content',
    position: $contentArea->anchor(Anchor::TopLeft, offsetX: 0.0, offsetY: 0.0),
);

$document->text()->write(
    text: 'Bottom-right content',
    position: $contentArea->anchor(Anchor::BottomRight, offsetX: -20.0, offsetY: 5.0),
);

安全區域(Safe Zone)

// 定義安全區域(頁面框內的額外保守邊距)
$safeZone = $document->layout()->getSafeZone(inset: 5.0);

// 確保文字在安全區域內
$document->text()->writeInBox(
    text: $criticalContent,
    box: $safeZone->toRectangle(),
);

自訂頁面區域

use NextPDF\Layout\NamedRegion;

// 定義命名的可重用區域
$document->layout()->defineRegion(
    name: 'header',
    region: NamedRegion::fromTop(height: 25.0),
);

$document->layout()->defineRegion(
    name: 'footer',
    region: NamedRegion::fromBottom(height: 20.0),
);

$document->layout()->defineRegion(
    name: 'sidebar',
    region: NamedRegion::fromRight(width: 50.0, offsetFromTop: 25.0, offsetFromBottom: 20.0),
);

// 在命名區域中渲染
$document->layout()->inRegion('header', function (Rectangle $area) use ($document): void {
    $document->text()->write(text: 'Header content', position: $area->topLeft());
});

格線系統

use NextPDF\Layout\Grid;

// 12 欄格線系統
$grid = Grid::create(
    columns: 12,
    gutterWidth: 5.0,
    availableWidth: $contentArea->width,
);

// 取得特定欄的矩形區域
$span4 = $grid->span(start: 1, end: 4); // 第 1 欄到第 4 欄
$span8 = $grid->span(start: 5, end: 12); // 第 5 欄到第 12 欄

參見