phpdftk API Documentation

PdfDoc
in package

Level 2 — friendly API over the PDF document object model.

PdfDoc wraps a PdfWriter and exposes one method per "thing a user wants to put in a document": pages, outlines, page labels, named destinations, info/metadata. Later phases extend this with annotation builders, form field builders, file attachments, viewer preferences, action factories, layers, gradients, and more.

The split between PdfDoc and PdfWriter is:

  • PdfDoc is about what is in the document (Catalog conveniences)
  • PdfWriter is about how bytes get written (fonts, images, content streams, signing, encryption, conformance, save)

Drop down to the underlying PdfWriter via writer() when you need direct byte/resource control (custom fonts, encryption, etc.).

Table of Contents

Methods

__construct()  : mixed
add3DAnnotation()  : ThreeDAnnotation
Add a 3D annotation. Caller supplies a pre-constructed {@see \Phpdftk\Pdf\Core\ThreeD\ThreeDStream} containing the U3D or PRC payload.
addCaret()  : CaretAnnotation
Add a caret annotation — small upward-pointing wedge typically used to mark an insertion point.
addCheckbox()  : ButtonField
Add a checkbox to the page. The export value (the string recorded as the field's `/V` when checked) defaults to `Yes`.
addChoiceField()  : ChoiceField
Add a drop-down (combo) or list-box choice field. `$options` carries the list of allowed `[value, label]` choices and the usual required / read-only flags.
addCircleAnnotation()  : CircleAnnotation
Add a circular / elliptical shape annotation — visible as a stroked ellipse inscribed in the rectangle.
addFreeText()  : FreeTextAnnotation
Add a free-text annotation — text drawn directly on the page (rather than in a popup like a sticky note). `$defaultAppearance` is the PDF "default appearance" string controlling font + colour (e.g. `/Helv 10 Tf 0 0 0 rg`).
addHighlight()  : HighlightAnnotation
Add a text-highlight annotation. `$quads` is a list of `Rectangle`s — one per highlighted span (typically each text line). The annotation's bounding rect is the union of all quads.
addInk()  : InkAnnotation
Add a free-form ink annotation. `$paths` is a list of strokes, each stroke a flat list of `[x0, y0, x1, y1, ...]` points.
addLayer()  : OCG
Register a new optional-content group (layer). The returned `OCG` is referenced from the catalog's `/OCProperties` /OCGs array; pass it to {@see Writer\Page::inLayer()} to tag drawing operations as belonging to this layer.
addLineAnnotation()  : LineAnnotation
Add a line annotation between two points.
addLinearGradient()  : ShadingPattern
Register a two-stop axial (linear) gradient. The returned {@see ShadingPattern} can be used as a fill via {@see Writer\Page::useGradient()}.
addLink()  : LinkAnnotation
Add a link annotation to a page.
addMovieAnnotation()  : MovieAnnotation
Add a movie annotation. Deprecated in PDF 2.0 in favour of Rich Media / Screen annotations; provided for legacy workflows.
addOutlineItem()  : PdfReference
Register an OutlineItem and return a reference to it. Callers are responsible for linking Prev/Next/First/Last/Parent.
addPage()  : Page
Add a new page. Friendly wrapper that returns the same {@see Page} handle as PdfWriter::addPage().
addPolygon()  : PolygonAnnotation
Add a polygon annotation. `$points` is a list of `[x, y]` pairs; the polygon is implicitly closed back to the first vertex.
addPolyline()  : PolyLineAnnotation
Add a polyline annotation — like a polygon but open (last point does not connect back to the first).
addRadialGradient()  : ShadingPattern
Register a two-stop radial gradient. `$inner` / `$outer` are concentric (or non-concentric) circles defining the gradient boundary.
addSignatureField()  : SignatureField
Add a signature field placeholder. Pair with {@see PdfWriter::setSigner()} to actually sign the document at generate time.
addSoundAnnotation()  : SoundAnnotation
Add a sound annotation. Caller supplies a pre-constructed {@see \Phpdftk\Pdf\Core\Multimedia\Sound} stream (with sample rate + bytes). Deprecated in PDF 2.0 — prefer Rich Media for new documents.
addSquare()  : SquareAnnotation
Add a rectangular shape annotation — visible as a stroked rectangle on the page.
addSquiggly()  : SquigglyAnnotation
Add a squiggly-underline annotation — wavy line below each text span.
addStamp()  : StampAnnotation
Add a rubber-stamp annotation. `$stampName` is the standard stamp identifier (`Approved`, `Confidential`, `Draft`, etc.).
addStickyNote()  : TextAnnotation
Add a sticky-note ("text") annotation — a small icon that opens a popup with `$content` text when clicked. `$point` is the lower-left corner; the rect defaults to a 16×16 box around it.
addStrikeout()  : StrikeOutAnnotation
Add a strikeout annotation — line through each text span.
addTextField()  : TextField
Add a single-line (or multi-line) text input to the page. The field is registered in the document's AcroForm and a Widget annotation is attached to the page's `/Annots` array.
addUnderlineAnnotation()  : UnderlineAnnotation
Add an underline annotation — visually similar to highlight but draws a line under each text span. `$quads` is one rect per span.
addWatermarkAnnotation()  : WatermarkAnnotation
Add a watermark annotation — fixed page-level overlay that doesn't print by default (PDF 1.7).
attachFile()  : FileSpec
Attach a file from disk. The file's bytes are read via {@see LocalFilesystem::readFile()} and embedded as an `EmbeddedFile`, wrapped in a `FileSpec`, and appended to the catalog's `/AF` (Associated Files) array.
attachFileBytes()  : FileSpec
Attach a file from in-memory bytes — useful when the source isn't on disk (generated XML for ZUGFeRD, downloaded content, etc.).
createBarcode()  : FormXObject
Build a reusable {@see FormXObject} containing a barcode rendering. The resulting template can be placed on multiple pages via `Writer\Page::drawTemplate()`.
createTemplate()  : FormXObject
Build a reusable Form XObject — a self-contained content stream that can be placed on multiple pages without re-emitting the underlying operators.
registerSpotColor()  : SpotColor
Register a spot color (a {@see Separation} color space). The `$cmykTint` parameter specifies the device-CMYK approximation used by viewers that don't have the spot ink — values are 0–1.
setAuthor()  : self
setCreator()  : self
setInfo()  : self
setKeywords()  : self
setMetadata()  : self
Attach an XMP metadata stream to the document catalog.
setNamedDestinations()  : self
Set named destinations on the document. Pass an associative array of name => Destination.
setOpenAction()  : self
Set the document's open action — executed by the viewer when the document is loaded. Typically used to jump to a specific page or run JavaScript on open. The action is registered as an indirect object; pass an instance from {@see Action}'s static factories.
setOutline()  : Outline
Register an Outline root and wire it to the Catalog. Returns the Outline for further configuration (setting First/Last/Count).
setPageLabels()  : self
Set a flat page-labels number tree on the Catalog. Pass an associative array of zero-based page index => PageLabel.
setSubject()  : self
setTitle()  : self
setViewerPreferences()  : self
Set the document's viewer preferences. Accepts either a pre-constructed {@see ViewerPreferences} object or a closure that receives a fresh instance and mutates it.
syncInfoToMetadata()  : self
Build and attach XMP metadata from the document's Info dictionary.
wrap()  : self
Wrap an existing PdfWriter — typically one already configured with conformance, signing, or encryption — and expose the friendly API on top of it.
writer()  : PdfWriter
Escape hatch: the underlying PdfWriter for byte/resource control.

Methods

addFreeText()

Add a free-text annotation — text drawn directly on the page (rather than in a popup like a sticky note). `$defaultAppearance` is the PDF "default appearance" string controlling font + colour (e.g. `/Helv 10 Tf 0 0 0 rg`).

public addFreeText(Page|Page $page, Rectangle $rect, string $content[, string $defaultAppearance = '/Helv 10 Tf 0 0 0 rg' ]) : FreeTextAnnotation
Parameters
$page : Page|Page
$rect : Rectangle
$content : string
$defaultAppearance : string = '/Helv 10 Tf 0 0 0 rg'
Return values
FreeTextAnnotation

addInk()

Add a free-form ink annotation. `$paths` is a list of strokes, each stroke a flat list of `[x0, y0, x1, y1, ...]` points.

public addInk(Page|Page $page, array<int, array<int, float>> $paths) : InkAnnotation
Parameters
$page : Page|Page
$paths : array<int, array<int, float>>
Return values
InkAnnotation

addLayer()

Register a new optional-content group (layer). The returned `OCG` is referenced from the catalog's `/OCProperties` /OCGs array; pass it to {@see Writer\Page::inLayer()} to tag drawing operations as belonging to this layer.

public addLayer(string $name[, bool $visible = true ]) : OCG

$visible controls the default state: visible layers go into the default config's /ON list, hidden ones into /OFF.

Parameters
$name : string
$visible : bool = true
Return values
OCG

addLineAnnotation()

Add a line annotation between two points.

public addLineAnnotation(Page|Page $page, float $x1, float $y1, float $x2, float $y2) : LineAnnotation
Parameters
$page : Page|Page
$x1 : float
$y1 : float
$x2 : float
$y2 : float
Return values
LineAnnotation

addLinearGradient()

Register a two-stop axial (linear) gradient. The returned {@see ShadingPattern} can be used as a fill via {@see Writer\Page::useGradient()}.

public addLinearGradient(Point $from, Point $to, array{float, float, float} $startRgb, array{float, float, float} $endRgb) : ShadingPattern
Parameters
$from : Point
$to : Point
$startRgb : array{float, float, float}

RGB at gradient origin.

$endRgb : array{float, float, float}

RGB at gradient end.

Return values
ShadingPattern

Add a link annotation to a page.

public addLink(Page|Page $page, Rectangle $rect, string|Destination|PdfReference $target[, BorderStyle|null $border = null ]) : LinkAnnotation

$target accepts:

  • string — treated as a URI; an inline /A action dict is built.
  • Destination — an explicit destination (use the named constructors Destination::fit($pageRef), Destination::xyz(...), etc.).
  • PdfReference — points to a named destination that has been registered via setNamedDestinations().
Parameters
$page : Page|Page
$rect : Rectangle
$target : string|Destination|PdfReference
$border : BorderStyle|null = null
Return values
LinkAnnotation

addPage()

Add a new page. Friendly wrapper that returns the same {@see Page} handle as PdfWriter::addPage().

public addPage([Rectangle|float $widthOrRect = 612 ][, float $height = 792 ]) : Page
Parameters
$widthOrRect : Rectangle|float = 612
$height : float = 792
Return values
Page

addPolygon()

Add a polygon annotation. `$points` is a list of `[x, y]` pairs; the polygon is implicitly closed back to the first vertex.

public addPolygon(Page|Page $page, array<int, array{float, float}> $points) : PolygonAnnotation
Parameters
$page : Page|Page
$points : array<int, array{float, float}>
Return values
PolygonAnnotation

addPolyline()

Add a polyline annotation — like a polygon but open (last point does not connect back to the first).

public addPolyline(Page|Page $page, array<int, array{float, float}> $points) : PolyLineAnnotation
Parameters
$page : Page|Page
$points : array<int, array{float, float}>
Return values
PolyLineAnnotation

addRadialGradient()

Register a two-stop radial gradient. `$inner` / `$outer` are concentric (or non-concentric) circles defining the gradient boundary.

public addRadialGradient(Point $innerCenter, float $innerRadius, Point $outerCenter, float $outerRadius, array{float, float, float} $startRgb, array{float, float, float} $endRgb) : ShadingPattern
Parameters
$innerCenter : Point
$innerRadius : float
$outerCenter : Point
$outerRadius : float
$startRgb : array{float, float, float}

RGB at inner radius.

$endRgb : array{float, float, float}

RGB at outer radius.

Return values
ShadingPattern

addSoundAnnotation()

Add a sound annotation. Caller supplies a pre-constructed {@see \Phpdftk\Pdf\Core\Multimedia\Sound} stream (with sample rate + bytes). Deprecated in PDF 2.0 — prefer Rich Media for new documents.

public addSoundAnnotation(Page|Page $page, Rectangle $rect, Sound $sound) : SoundAnnotation
Parameters
$page : Page|Page
$rect : Rectangle
$sound : Sound
Return values
SoundAnnotation

addStickyNote()

Add a sticky-note ("text") annotation — a small icon that opens a popup with `$content` text when clicked. `$point` is the lower-left corner; the rect defaults to a 16×16 box around it.

public addStickyNote(Page|Page $page, float $x, float $y, string $content[, string|null $iconName = null ]) : TextAnnotation
Parameters
$page : Page|Page
$x : float
$y : float
$content : string
$iconName : string|null = null
Return values
TextAnnotation

addTextField()

Add a single-line (or multi-line) text input to the page. The field is registered in the document's AcroForm and a Widget annotation is attached to the page's `/Annots` array.

public addTextField(string $name, Page|Page $page, Rectangle $rect[, TextFieldOptions|null $options = null ]) : TextField

Field flags (/Ff) are derived from TextFieldOptions:

  • required → bit 2 (0x0002)
  • readOnly → bit 1 (0x0001)
  • multiline → bit 13 (0x1000)
  • password → bit 14 (0x2000)
Parameters
$name : string
$page : Page|Page
$rect : Rectangle
$options : TextFieldOptions|null = null
Return values
TextField

attachFile()

Attach a file from disk. The file's bytes are read via {@see LocalFilesystem::readFile()} and embedded as an `EmbeddedFile`, wrapped in a `FileSpec`, and appended to the catalog's `/AF` (Associated Files) array.

public attachFile(string $path[, string|null $description = null ][, string|null $mimeType = null ][, string|null $relationship = null ]) : FileSpec

$relationship populates /AFRelationship — the PDF 2.0 hint to viewers about the file's role. ZUGFeRD invoices use Alternative for the embedded XML; common values are Source, Data, Alternative, Supplement, EncryptedPayload, and FormData.

Parameters
$path : string
$description : string|null = null
$mimeType : string|null = null
$relationship : string|null = null
Return values
FileSpec

attachFileBytes()

Attach a file from in-memory bytes — useful when the source isn't on disk (generated XML for ZUGFeRD, downloaded content, etc.).

public attachFileBytes(string $name, string $bytes[, string|null $description = null ][, string|null $mimeType = null ][, string|null $relationship = null ]) : FileSpec
Parameters
$name : string
$bytes : string
$description : string|null = null
$mimeType : string|null = null
$relationship : string|null = null
Return values
FileSpec

createBarcode()

Build a reusable {@see FormXObject} containing a barcode rendering. The resulting template can be placed on multiple pages via `Writer\Page::drawTemplate()`.

public createBarcode(Symbology $symbology, string $data[, BarcodeOptions|null $options = null ]) : FormXObject

Only Symbology::Code128 is implemented in v1; other cases throw at render time.

Parameters
$symbology : Symbology
$data : string
$options : BarcodeOptions|null = null
Return values
FormXObject

createTemplate()

Build a reusable Form XObject — a self-contained content stream that can be placed on multiple pages without re-emitting the underlying operators.

public createTemplate(Rectangle $bbox, callable(ContentStream): void $draw) : FormXObject

The closure receives a fresh ContentStream sized to $bbox (origin at bbox->x, bbox->y). Any drawing operators the closure adds are captured into the FormXObject's stream; resources (fonts, images) used inside the template must be registered on the FormXObject's own resource dict — for v1, the caller passes pre-registered Font handles into the closure if needed and accepts that the template inherits resources from the placing page.

Parameters
$bbox : Rectangle
$draw : callable(ContentStream): void
Return values
FormXObject

registerSpotColor()

Register a spot color (a {@see Separation} color space). The `$cmykTint` parameter specifies the device-CMYK approximation used by viewers that don't have the spot ink — values are 0–1.

public registerSpotColor(string $name, array{float, float, float, float} $cmykTint) : SpotColor

Use the returned Separation with Page::useSpotColor() to attach it to a page's resources and obtain the resource name for content-stream ops:

$sep = $doc->registerSpotColor('Pantone 185 C', [0, 0.85, 0.6, 0]); $name = $page->useSpotColor($sep); $page->contentStream() ->setFillColorSpace($name) ->setFillColor(1.0) // full tint ->rectangle(72, 600, 200, 80) ->fill();

Parameters
$name : string
$cmykTint : array{float, float, float, float}
Return values
SpotColor

setAuthor()

public setAuthor(string $author) : self
Parameters
$author : string
Return values
self

setCreator()

public setCreator(string $creator) : self
Parameters
$creator : string
Return values
self

setInfo()

public setInfo(Info $info) : self
Parameters
$info : Info
Return values
self

setKeywords()

public setKeywords(string $keywords) : self
Parameters
$keywords : string
Return values
self

setMetadata()

Attach an XMP metadata stream to the document catalog.

public setMetadata(string $xmpXml) : self
Parameters
$xmpXml : string
Return values
self

setNamedDestinations()

Set named destinations on the document. Pass an associative array of name => Destination.

public setNamedDestinations(array<string, Destination$destinations) : self
Parameters
$destinations : array<string, Destination>
Return values
self

setOpenAction()

Set the document's open action — executed by the viewer when the document is loaded. Typically used to jump to a specific page or run JavaScript on open. The action is registered as an indirect object; pass an instance from {@see Action}'s static factories.

public setOpenAction(Action $action) : self
Parameters
$action : Action
Return values
self

setOutline()

Register an Outline root and wire it to the Catalog. Returns the Outline for further configuration (setting First/Last/Count).

public setOutline(Outline $outline) : Outline
Parameters
$outline : Outline
Return values
Outline

setPageLabels()

Set a flat page-labels number tree on the Catalog. Pass an associative array of zero-based page index => PageLabel.

public setPageLabels(array<int, PageLabel$labels) : self

Example: [0 => $frontMatter, 4 => $mainContent]

Parameters
$labels : array<int, PageLabel>
Return values
self

setSubject()

public setSubject(string $subject) : self
Parameters
$subject : string
Return values
self

setTitle()

public setTitle(string $title) : self
Parameters
$title : string
Return values
self

setViewerPreferences()

Set the document's viewer preferences. Accepts either a pre-constructed {@see ViewerPreferences} object or a closure that receives a fresh instance and mutates it.

public setViewerPreferences(ViewerPreferences|Closure $prefs) : self

Closure form: $doc->setViewerPreferences(function (ViewerPreferences $vp): void { $vp->displayDocTitle = true; $vp->fitWindow = true; });

Parameters
$prefs : ViewerPreferences|Closure
Return values
self

syncInfoToMetadata()

Build and attach XMP metadata from the document's Info dictionary.

public syncInfoToMetadata() : self

Syncs Title, Author, Subject, Creator, Producer from the Info dict into XMP properties (dc:title, dc:creator, dc:description, xmp:CreatorTool, pdf:Producer) and attaches the result as a MetadataStream on the Catalog.

Return values
self

wrap()

Wrap an existing PdfWriter — typically one already configured with conformance, signing, or encryption — and expose the friendly API on top of it.

public static wrap(PdfWriter $writer) : self
Parameters
$writer : PdfWriter
Return values
self

writer()

Escape hatch: the underlying PdfWriter for byte/resource control.

public writer() : PdfWriter
Return values
PdfWriter

        
On this page

Search results