Skip to content

Document API

Document 是 TCPDF-Next 的主要入口类。它通过 12 个 Trait 组合了所有 PDF 操作功能,并支持 Fluent Chaining(链式调用)。

完整类名TcpdfNext\Document

php
use TcpdfNext\Document;

$doc = Document::create();

静态工厂方法

php
public static function create(?Config $config = null, ?FontManager $fontManager = null): static

创建新的 Document 实例。所有参数均为可选,使用默认值即可快速上手。


Trait 1:DocumentMetadata

管理文档元数据(PDF Info Dictionary)。

php
public function setTitle(string $title): static
public function setAuthor(string $author): static
public function setSubject(string $subject): static
public function setKeywords(string $keywords): static
public function setCreator(string $creator): static
public function setCreationDate(\DateTimeInterface $date): static
public function setModificationDate(\DateTimeInterface $date): static
public function setLanguage(string $lang): static          // 例如 'zh-CN'
public function getTitle(): string
public function getAuthor(): string

Trait 2:PageManagement

页面的新增、切换与查询。

php
public function addPage(
    ?PageSize $size = null,
    ?Orientation $orientation = null
): static

public function getCurrentPage(): int             // 当前页码(从 1 开始)
public function getTotalPages(): int              // 总页数
public function goToPage(int $pageNumber): static // 切换到指定页面
public function deletePage(int $pageNumber): static

public function setPageSize(PageSize $size): static
public function setOrientation(Orientation $orientation): static
public function setMargins(Margin $margins): static
public function setAutoPageBreak(bool $enabled, float $margin = 20): static

Trait 3:TextOperations

文字输出与样式配置。

php
public function text(string $text, float $x, ?float $y = null): static
public function cell(
    float $width,
    float $height,
    string $text = '',
    bool $border = false,
    string $align = 'L',       // L | C | R
    bool $fill = false
): static

public function multiCell(
    float $width,
    string $text,
    bool $border = false,
    string $align = 'J',       // L | C | R | J
    float $lineHeight = 1.2,
    float $maxHeight = 0       // 0 = 不限高度
): static

public function setFont(string $family, float $size = 12, string $style = ''): static
public function setTextColor(Color $color): static
public function setTextStyle(TextStyle $style): static
public function setTextRenderMode(TextRenderMode $mode): static
public function setTextShadow(TextShadow $shadow): static
public function setTextDirection(TextDirection $direction): static
public function setCharacterSpacing(float $spacing): static
public function setWordSpacing(float $spacing): static

Trait 4:GraphicsOperations

矢量图形绘制与图片嵌入。

php
// 绘图基元
public function line(float $x1, float $y1, float $x2, float $y2): static
public function rect(float $x, float $y, float $width, float $height, string $style = 'D'): static
public function roundedRect(
    float $x, float $y, float $width, float $height,
    float $radius, string $style = 'DF'
): static
public function circle(float $cx, float $cy, float $radius, string $style = 'DF'): static
public function ellipse(float $cx, float $cy, float $rx, float $ry, string $style = 'DF'): static
public function arc(float $cx, float $cy, float $radius, float $startAngle, float $endAngle): static
public function polygon(array $points, string $style = 'DF'): static
public function regularPolygon(float $cx, float $cy, float $radius, int $sides, string $style = 'DF'): static

// 色彩与线条
public function setDrawColor(Color $color): static
public function setFillColor(Color $color): static
public function setLineWidth(float $width): static
public function setDash(array $pattern): static
public function setAlpha(float $opacity): static

// 图形状态
public function saveState(): static
public function restoreState(): static
public function transform(TransformMatrix $matrix): static

// 图片
public function image(
    string $file,
    float $x, float $y,
    float $width, float $height = 0   // 0 = 按比例计算
): static

// SVG / EPS
public function importSvg(string $file, float $x, float $y, float $width, float $height = 0): static
public function importSvgString(string $svg, float $x, float $y, float $width): static
public function importEps(string $file, float $x, float $y, float $width): static

Trait 5:HeaderFooterCallbacks

页眉与页脚的定义与控制。

php
public function setHeader(HeaderFooter $header): static
public function setFooter(HeaderFooter $footer): static
public function disableHeader(): static
public function enableHeader(): static
public function disableFooter(): static
public function enableFooter(): static

Trait 6:ColumnOperations

多栏排版控制。

php
public function setColumnLayout(ColumnLayout $layout): static
public function nextColumn(): static               // 跳到下一栏
public function resetColumns(): static             // 重置到第一栏

Trait 7:HtmlRendering

HTML / CSS 内容写入。

php
public function writeHtml(
    string $html,
    float $x = 0,
    float $y = 0,
    float $width = 0           // 0 = 使用可用宽度
): static

Trait 8:FormFields

交互表单字段创建。

php
public function addTextField(
    string $name,
    float $x, float $y,
    float $width, float $height,
    string $defaultValue = '',
    ?string $placeholder = null,
    bool $multiline = false,
    bool $password = false,
    bool $required = false,
    ?int $maxLength = null,
    ?float $fontSize = null,
    ?string $format = null,
    ?FormStyle $style = null,
    ?string $onChangeScript = null,
    ?string $onValidateScript = null
): static

public function addCheckBox(
    string $name,
    float $x, float $y,
    float $size = 5,
    bool $checked = false
): static

public function addRadioButton(
    string $name,
    string $value,
    float $x, float $y,
    float $size = 5,
    bool $selected = false
): static

public function addComboBox(
    string $name,
    float $x, float $y,
    float $width, float $height,
    array $options,
    string $selectedValue = '',
    bool $editable = false
): static

public function addListBox(
    string $name,
    float $x, float $y,
    float $width, float $height,
    array $options,
    bool $multiSelect = false,
    array $selectedValues = []
): static

public function addPushButton(
    string $name,
    float $x, float $y,
    float $width, float $height,
    string $caption,
    string $action,               // 'submitForm' | 'resetForm' | 'javascript'
    ?string $url = null,
    ?string $script = null
): static

public function addSignatureField(
    string $name,
    float $x, float $y,
    float $width, float $height
): static

Trait 9:NavigationFeatures

书签、链接、目录与附件。

php
// 书签
public function addBookmark(
    string $title,
    int $level = 0,
    ?float $y = null,
    ?Color $color = null,
    string $style = '',
    bool $open = true
): static

// 超链接
public function addLink(
    string $url,
    float $x, float $y,
    float $width, float $height,
    ?string $text = null
): static
public function createInternalLink(): int
public function addInternalLink(int $linkId, float $x, float $y, float $width, float $height): static
public function setInternalLinkDestination(int $linkId, float $y = 0): static
public function addNamedDestination(string $name, int $page, float $y = 0): static

// 目录
public function insertToc(TocGenerator $toc, int $atPage = 1): static

// 注解
public function addTextAnnotation(
    float $x, float $y,
    float $width, float $height,
    string $text,
    string $icon = 'Comment',
    ?Color $color = null,
    bool $open = false
): static
public function addHighlightAnnotation(
    float $x, float $y, float $width, float $height,
    ?Color $color = null, float $opacity = 0.5, string $text = ''
): static
public function addStampAnnotation(
    float $x, float $y, float $width, float $height,
    string $stampType = 'Approved', string $text = ''
): static

// 附件
public function addAttachment(
    string $file,
    ?string $name = null,
    ?string $description = null,
    ?string $mimeType = null
): static
public function addAttachmentFromString(
    string $data, string $name,
    ?string $description = null,
    ?string $mimeType = null
): static

Trait 10:BarcodeOperations

一维与二维条码。

php
public function barcode1D(
    string $code,
    string $type,                  // 'C128' | 'EAN13' | 'C39' 等
    float $x, float $y,
    float $width, float $height,
    ?Color $color = null,
    bool $showText = false
): static

public function qrCode(
    string $data,
    float $x, float $y,
    float $size,
    string $errorCorrectionLevel = 'M',   // L | M | Q | H
    ?Color $color = null,
    ?Color $backgroundColor = null
): static

public function dataMatrix(string $data, float $x, float $y, float $size): static

public function pdf417(
    string $data,
    float $x, float $y,
    float $width, float $height,
    int $errorCorrectionLevel = 5,
    int $columns = 4
): static

Trait 11:SecurityFeatures

加密、数字签名与 PDF/A 合规。

php
// 加密
public function encrypt(
    string $userPassword,
    string $ownerPassword,
    array $permissions = []          // Permission[] 枚举数组
): static

// 数字签名
public function sign(
    string $certificate,
    string $privateKey,
    ?string $password = null,
    SignatureLevel $level = SignatureLevel::PAdES_B_B,
    ?string $reason = null,
    ?string $location = null,
    ?string $contactInfo = null,
    ?string $field = null,
    ?string $timestampServer = null,
    ?array $appearance = null
): static

// PDF/A 合规
public function setPdfACompliance(string $level): static      // 'PDF/A-4' | 'PDF/A-4f'
public function setOutputIntent(OutputIntent $intent): static
public function setXmpMetadata(XmpMetadata $xmp): static
public function setDss(DssManager $dss): static

// 无障碍
public function setTagged(bool $enabled): static
public function beginTag(string $type, array $attributes = []): static
public function endTag(): static
public function beginArtifact(string $type): static
public function endArtifact(): static

Trait 12:OutputMethods

文档输出与序列化。

php
public function save(string $filepath): void
public function toString(): string                   // 取得原始 PDF 字节
public function output(
    string $name = 'document.pdf',
    OutputDestination $dest = OutputDestination::Inline
): string|void

public function setViewerPreferences(ViewerPreferences $prefs): static

// 图层
public function createLayer(
    string $name,
    bool $visible = true,
    bool $printable = true
): Layer
public function beginLayer(Layer $layer): static
public function endLayer(): static

// JavaScript
public function addDocumentJavaScript(JavaScriptAction $action): static
public function setPageOpenAction(JavaScriptAction $action): static

// 关联文件(PDF 2.0)
public function addAssociatedFile(AssociatedFile $file): static

使用示例

以下示例展示多个 Trait 的组合使用:

php
use TcpdfNext\Document;
use TcpdfNext\ValueObjects\{PageSize, Margin, Color};
use TcpdfNext\Contracts\{Orientation, SignatureLevel};

$doc = Document::create()
    // DocumentMetadata
    ->setTitle('合同文件')
    ->setAuthor('法务部')
    ->setLanguage('zh-CN')

    // PageManagement
    ->setPageSize(PageSize::A4)
    ->setMargins(Margin::symmetric(horizontal: 20, vertical: 25))
    ->addPage()

    // TextOperations
    ->setFont('NotoSansTC', size: 16, style: 'B')
    ->setTextColor(Color::rgb(r: 0, g: 51, b: 102))
    ->text('服务合同书', x: 70, y: 25)

    // NavigationFeatures
    ->addBookmark(title: '合同书', level: 0)

    // SecurityFeatures
    ->sign(
        certificate: file_get_contents('cert.pem'),
        privateKey: file_get_contents('key.pem'),
        level: SignatureLevel::PAdES_B_LTA,
        reason: '核准文件',
        timestampServer: 'https://freetsa.org/tsr'
    )

    // OutputMethods
    ->save('contract.pdf');

相关页面

以 LGPL-3.0-or-later 许可证发布。