文字渲染¶
TextRenderer 是 NextPDF 輸出文字的主要 API。它整合字型登錄、雙向文字解析器與文字預處理管線,確保所有文字在進入 PDF 串流前已完成安全處理。
基本文字輸出¶
use NextPDF\ValueObjects\Position;
$document->text()->write(
text: 'Hello, NextPDF!',
position: Position::at(x: 20.0, y: 50.0),
);
字型與樣式¶
use NextPDF\Typography\FontStyle;
$document->text()->write(
text: 'Invoice Total: $1,234.56',
position: Position::at(x: 20.0, y: 80.0),
style: FontStyle::create(
fontFamily: 'Helvetica',
fontSize: 14.0,
bold: true,
italic: false,
color: [0, 0, 0], // RGB 0–255
),
);
文字陰影¶
use NextPDF\Content\TextShadow;
$document->text()->write(
text: 'Report Title',
position: Position::at(x: 20.0, y: 30.0),
shadow: TextShadow::create(
offsetX: 1.0,
offsetY: -1.0,
blur: 2.0,
color: [100, 100, 100],
),
);
多行文字與文字框¶
use NextPDF\ValueObjects\Rectangle;
use NextPDF\Content\TextAlignment;
// 在矩形區域內自動換行
$document->text()->writeInBox(
text: 'This is a long paragraph that will automatically wrap within the specified bounding box.',
box: Rectangle::fromXY(x: 20.0, y: 50.0, width: 150.0, height: 80.0),
alignment: TextAlignment::Justify,
);
文字預處理管線¶
NextPDF 在文字進入 PDF 串流前,會通過 TextPreprocessorInterface 管線。這是安全性關鍵功能——敏感文字不會出現在字型子集或 ToUnicode CMap 中:
use NextPDF\Contracts\TextPreprocessorInterface;
// 自訂預處理器(例如:自動替換敏感詞)
final class RedactionPreprocessor implements TextPreprocessorInterface
{
public function process(string $text, ProcessingContext $ctx): string
{
return preg_replace('/\b\d{4}-\d{4}-\d{4}-\d{4}\b/', '****-****-****-****', $text);
}
}
$process->registerTextPreprocessor(new RedactionPreprocessor());
座標與單位¶
use NextPDF\ValueObjects\Position;
use NextPDF\ValueObjects\Unit;
// 使用毫米座標(預設)
$pos = Position::at(x: 20.0, y: 50.0); // Unit::Millimeter
// 使用 PDF 點數
$pos = Position::at(x: 56.69, y: 141.73, unit: Unit::Point);