phpdftk API Documentation

Pdf
in package

High-level PDF document builder — **zero PDF object-model knowledge required**.

Pdf is a stateful, cursor-driven builder on top of PdfWriter. It maintains a current page, a text cursor, and a default font; each call flows content downward from the top margin, automatically breaking to a new page when the content column fills up.

Example

$pdf = new Pdf();                              // Letter, 72pt margins, Helvetica 11
$pdf->addHeading('Welcome', 1);
$pdf->addText('This is body text. It wraps automatically to the content');
$pdf->addText('column width, and overflowing content starts a new page.');
$pdf->addSpacer(12);
$pdf->addImage('/path/to/photo.jpg', width: 300);
$pdf->save('/out.pdf');

Output modes

Three mutually-exclusive ways to emit the finished document:

  • save(string $path) — write to a file
  • toBytes(): string — get the bytes as a string
  • writeTo($resource): int — write to an open stream resource

Scope

Phase 1 handles the 80% case: word-wrapped body text, H1–H6 headings, images with auto-scaling, spacers, horizontal rules, explicit and automatic page breaks, and Left/Center/Right alignment. Fonts are limited to the 14 standard PDF fonts (Helvetica / Times / Courier families plus Symbol and ZapfDingbats). For custom TrueType fonts, embedded images with precise transforms, tables, or absolute-positioned graphics, drop to the underlying PdfWriter via writer().

Table of Contents

Methods

__construct()  : mixed
addBarcode()  : self
Render a barcode in the flow at the current cursor. Width comes from the rendered bitmap (modules × moduleWidth + quiet zones); `align` controls horizontal placement within the column.
addCallout()  : self
Add a callout block at the current cursor — a coloured panel with a left bar, optional title row, and wrapped body text. The built-in {@see CalloutType} cases (`Note`, `Tip`, `Warning`, `Danger`) carry default bar / background colours; override any of them via {@see CalloutStyle}.
addHeading()  : self
Add a heading (H1–H6) using the theme's heading style for the given level.
addHtml()  : self
Render an HTML + CSS document into the PDF as a sequence of fresh pages, then invalidate the cursor so subsequent `addText` / `addHeading` / etc. start on a new page.
addImage()  : self
Add an image. If neither width nor height is given, the image is placed at its natural size in points (1 image pixel = 1 point).
addList()  : self
Add a bullet list at the current cursor. Items are plain strings or nested {@see ListBlock}s; nested blocks indent one level deeper.
addNumberedList()  : self
Add a numbered list (`1. … 2. …`). Numbering restarts at each nested level.
addPage()  : self
Start a new page. The first `add*` call will also start a page automatically if one has not yet been created, so calling this explicitly is only required when you want to force a page break or use a non-default size.
addQuote()  : self
Add a blockquote at the current cursor: indented text in italic with a coloured vertical bar down the left side. The body paginates like `addText`; the bar is drawn once per page the quote occupies.
addRule()  : self
Add a horizontal rule spanning the current content column.
addSpacer()  : self
Add vertical whitespace (points).
addTable()  : self
Add a tabular block of content. The table is rendered at the current cursor, with rows auto-paginating across page breaks.
addText()  : self
Add a paragraph of body text. Text is word-wrapped at the current content column width and flows downward from the cursor. If a paragraph runs past the bottom margin, the remaining lines continue on a new automatically-created page.
attachFile()  : self
Attach a file from disk to the document. Forwards to {@see PdfDoc::attachFile()}.
doc()  : PdfDoc
Escape hatch to Level 2: returns the underlying {@see PdfDoc} so callers can use friendly wrappers (annotations, form fields, file attachments, viewer prefs, etc.) without leaving the flow-builder context.
enableOutline()  : self
Enable automatic outline (bookmarks) generation from `addHeading()` calls. Each heading registers an `OutlineItem` with a destination pointing at the current page + y; heading level controls the parent → child nesting (level 2 nests under the previous level 1, etc.).
getEncodingWarnings()  : array<int, string>
Codepoints that were substituted with `?` because the active font's encoding could not represent them. Useful after building a document to confirm that no unintended replacement characters slipped in.
getPdfVersion()  : PdfVersion
getTheme()  : Theme
newPage()  : self
Force a page break. Equivalent to `addPage()` with the current size.
save()  : void
setAuthor()  : self
setColumns()  : self
Split the body region into `$count` columns separated by `$gutter` points. Flow content (text, lists, tables, callouts) fills the current column first, then advances to the next column when overflow occurs; a page break only happens after the last column on a page overflows.
setCreator()  : self
setFont()  : self
Set the default body font for subsequent content. Accepts one of the standard 14 PDF font families: Helvetica, Times, Courier, Symbol, ZapfDingbats.
setFooter()  : self
Register a closure invoked on every page after flow content is placed, to draw the footer region. See {@see setHeader()}.
setHeader()  : self
Register a closure invoked on every page after flow content is placed. The closure receives a {@see PageContext} with the current page number, total page count, and a {@see Page} handle for drawing into the header region.
setKeywords()  : self
setOpenAction()  : self
Set the document's open action — executed by the viewer when the file is loaded. Forwards to {@see PdfDoc::setOpenAction()}.
setSubject()  : self
setTheme()  : self
setTitle()  : self
setViewerPreferences()  : self
Set the document's viewer preferences (display options the reader honours when opening the file). Forwards to {@see PdfDoc::setViewerPreferences()}.
setWatermark()  : self
Set a watermark drawn on every page. A string is rendered as centered diagonal grey text; a closure is invoked per page with a {@see PageContext} for full control.
showPageNumbers()  : self
Show page numbers in the footer of every page. Sugar over {@see setFooter()} that uses `PageContext::$totalPages` from the deferred decorator pass, so `'Page %d of %d'`-style formats work without manual two-pass logic.
toBytes()  : string
writer()  : PdfWriter
Escape hatch to Level 1: returns the underlying {@see PdfWriter} for byte/resource control (custom fonts, encryption, signing, conformance). Equivalent to `doc()->writer()`.
writeTo()  : int

Methods

addBarcode()

Render a barcode in the flow at the current cursor. Width comes from the rendered bitmap (modules × moduleWidth + quiet zones); `align` controls horizontal placement within the column.

public addBarcode(Symbology $symbology, string $data[, BarcodeOptions|null $options = null ][, Alignment $align = Alignment::Left ]) : self

For multi-document reuse, prefer PdfDoc::createBarcode() + Writer\Page::drawTemplate().

Parameters
$symbology : Symbology
$data : string
$options : BarcodeOptions|null = null
$align : Alignment = Alignment::Left
Return values
self

addCallout()

Add a callout block at the current cursor — a coloured panel with a left bar, optional title row, and wrapped body text. The built-in {@see CalloutType} cases (`Note`, `Tip`, `Warning`, `Danger`) carry default bar / background colours; override any of them via {@see CalloutStyle}.

public addCallout(string $text[, CalloutType $type = CalloutType::Note ][, CalloutStyle|null $style = null ]) : self

In v1, callouts render on a single page — they auto-advance to a new page if the current one can't fit them, but they don't split mid-content. Callouts taller than a single page throw.

Parameters
$text : string
$type : CalloutType = CalloutType::Note
$style : CalloutStyle|null = null
Return values
self

addHeading()

Add a heading (H1–H6) using the theme's heading style for the given level.

public addHeading(string $text[, int $level = 1 ]) : self
Parameters
$text : string
$level : int = 1
Return values
self

addHtml()

Render an HTML + CSS document into the PDF as a sequence of fresh pages, then invalidate the cursor so subsequent `addText` / `addHeading` / etc. start on a new page.

public addHtml(string $html[, string|null $css = null ][, OpenTypeData|null $font = null ]) : self

The HTML renderer ships in phpdftk/html-to-pdf and depends on phpdftk/pdf-writer — so to avoid a circular composer dependency, this method only works when that package is installed. The class lookup happens lazily on first call; absent the package, the method throws a helpful RuntimeException.

Note: this does not try to fit content under the current cursor. For inline HTML rendering at the cursor position, drop down to Phpdftk\HtmlToPdf\Renderer directly and pass Pdf::writer() to renderInto().

Parameters
$html : string
$css : string|null = null
$font : OpenTypeData|null = null
Return values
self

addImage()

Add an image. If neither width nor height is given, the image is placed at its natural size in points (1 image pixel = 1 point).

public addImage(string $path[, float|null $width = null ][, float|null $height = null ][, Alignment $align = Alignment::Left ]) : self

If one dimension is given the other is scaled proportionally. If both are given the image is stretched to fit.

Parameters
$path : string
$width : float|null = null
$height : float|null = null
$align : Alignment = Alignment::Left
Return values
self

addList()

Add a bullet list at the current cursor. Items are plain strings or nested {@see ListBlock}s; nested blocks indent one level deeper.

public addList(array<int, string|ListBlock$items[, ListStyle|null $style = null ]) : self

Long items wrap at the available column width; lists auto-paginate item-by-item.

Parameters
$items : array<int, string|ListBlock>
$style : ListStyle|null = null
Return values
self

addNumberedList()

Add a numbered list (`1. … 2. …`). Numbering restarts at each nested level.

public addNumberedList(array<int, string|ListBlock$items[, ListStyle|null $style = null ]) : self
Parameters
$items : array<int, string|ListBlock>
$style : ListStyle|null = null
Return values
self

addPage()

Start a new page. The first `add*` call will also start a page automatically if one has not yet been created, so calling this explicitly is only required when you want to force a page break or use a non-default size.

public addPage([PageSize|null $size = null ]) : self
Parameters
$size : PageSize|null = null
Return values
self

addQuote()

Add a blockquote at the current cursor: indented text in italic with a coloured vertical bar down the left side. The body paginates like `addText`; the bar is drawn once per page the quote occupies.

public addQuote(string $text[, TextStyle|null $style = null ]) : self

Override font / colour / alignment via TextStyle. If the style doesn't specify italic, italic is applied by default — that's the visual signature of a blockquote.

Parameters
$text : string
$style : TextStyle|null = null
Return values
self

addRule()

Add a horizontal rule spanning the current content column.

public addRule([float $lineWidth = 0.5 ]) : self
Parameters
$lineWidth : float = 0.5
Return values
self

addSpacer()

Add vertical whitespace (points).

public addSpacer(float $points) : self
Parameters
$points : float
Return values
self

addTable()

Add a tabular block of content. The table is rendered at the current cursor, with rows auto-paginating across page breaks.

public addTable(array<int, array<int, string>> $rows[, array<int, float>|null $columnWidths = null ][, array<int, string>|null $headerRow = null ][, TableStyle|null $style = null ]) : self

When $headerRow is provided, it repeats at the top of every page the table occupies.

$columnWidths is a list of absolute point widths; pass null to split the content column evenly across the inferred column count. The widths must sum to at most the content column width.

Parameters
$rows : array<int, array<int, string>>
$columnWidths : array<int, float>|null = null
$headerRow : array<int, string>|null = null
$style : TableStyle|null = null
Return values
self

addText()

Add a paragraph of body text. Text is word-wrapped at the current content column width and flows downward from the cursor. If a paragraph runs past the bottom margin, the remaining lines continue on a new automatically-created page.

public addText(string $text[, TextStyle|null $style = null ]) : self
Parameters
$text : string
$style : TextStyle|null = null
Return values
self

attachFile()

Attach a file from disk to the document. Forwards to {@see PdfDoc::attachFile()}.

public attachFile(string $path[, string|null $description = null ][, string|null $mimeType = null ][, string|null $relationship = null ]) : self
Parameters
$path : string
$description : string|null = null
$mimeType : string|null = null
$relationship : string|null = null
Return values
self

doc()

Escape hatch to Level 2: returns the underlying {@see PdfDoc} so callers can use friendly wrappers (annotations, form fields, file attachments, viewer prefs, etc.) without leaving the flow-builder context.

public doc() : PdfDoc
Return values
PdfDoc

enableOutline()

Enable automatic outline (bookmarks) generation from `addHeading()` calls. Each heading registers an `OutlineItem` with a destination pointing at the current page + y; heading level controls the parent → child nesting (level 2 nests under the previous level 1, etc.).

public enableOutline([bool $enabled = true ]) : self

No-op when called before any heading exists. Disable later with enableOutline(false) to stop recording further headings.

Parameters
$enabled : bool = true
Return values
self

getEncodingWarnings()

Codepoints that were substituted with `?` because the active font's encoding could not represent them. Useful after building a document to confirm that no unintended replacement characters slipped in.

public getEncodingWarnings() : array<int, string>
Return values
array<int, string>

newPage()

Force a page break. Equivalent to `addPage()` with the current size.

public newPage() : self
Return values
self

save()

public save(string $path) : void
Parameters
$path : string

setAuthor()

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

setColumns()

Split the body region into `$count` columns separated by `$gutter` points. Flow content (text, lists, tables, callouts) fills the current column first, then advances to the next column when overflow occurs; a page break only happens after the last column on a page overflows.

public setColumns(int $count[, float $gutter = 12.0 ]) : self

Set $count = 1 to return to single-column flow. Calling this mid-document is allowed but only affects content added after the call; already-rendered content stays where it was placed.

Parameters
$count : int
$gutter : float = 12.0
Return values
self

setCreator()

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

setFont()

Set the default body font for subsequent content. Accepts one of the standard 14 PDF font families: Helvetica, Times, Courier, Symbol, ZapfDingbats.

public setFont(string $family, float $size[, bool $bold = false ][, bool $italic = false ]) : self
Parameters
$family : string
$size : float
$bold : bool = false
$italic : bool = false
Return values
self

setFooter()

Register a closure invoked on every page after flow content is placed, to draw the footer region. See {@see setHeader()}.

public setFooter(Closure $footer) : self
Parameters
$footer : Closure
Return values
self

setHeader()

Register a closure invoked on every page after flow content is placed. The closure receives a {@see PageContext} with the current page number, total page count, and a {@see Page} handle for drawing into the header region.

public setHeader(Closure $header) : self

The body region shrinks by Theme::headerHeight to leave room for the header; configure that on your theme if you want a non-zero reserved area.

Parameters
$header : Closure
Return values
self

setKeywords()

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

setOpenAction()

Set the document's open action — executed by the viewer when the file is loaded. Forwards to {@see PdfDoc::setOpenAction()}.

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

setSubject()

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

setTheme()

public setTheme(Theme $theme) : self
Parameters
$theme : Theme
Return values
self

setTitle()

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

setViewerPreferences()

Set the document's viewer preferences (display options the reader honours when opening the file). Forwards to {@see PdfDoc::setViewerPreferences()}.

public setViewerPreferences(ViewerPreferences|Closure $prefs) : self
Parameters
$prefs : ViewerPreferences|Closure
Return values
self

setWatermark()

Set a watermark drawn on every page. A string is rendered as centered diagonal grey text; a closure is invoked per page with a {@see PageContext} for full control.

public setWatermark(string|Closure $textOrFn[, float $opacity = 0.2 ][, float $angleDeg = 45.0 ]) : self
Parameters
$textOrFn : string|Closure
$opacity : float = 0.2
$angleDeg : float = 45.0
Return values
self

showPageNumbers()

Show page numbers in the footer of every page. Sugar over {@see setFooter()} that uses `PageContext::$totalPages` from the deferred decorator pass, so `'Page %d of %d'`-style formats work without manual two-pass logic.

public showPageNumbers([string $format = 'Page %d of %d' ][, Alignment $align = Alignment::Center ][, float $fontSize = 9.0 ]) : self

Set Theme::footerHeight to reserve space so the page number doesn't overlap body content.

Parameters
$format : string = 'Page %d of %d'
$align : Alignment = Alignment::Center
$fontSize : float = 9.0
Return values
self

toBytes()

public toBytes() : string
Return values
string

writer()

Escape hatch to Level 1: returns the underlying {@see PdfWriter} for byte/resource control (custom fonts, encryption, signing, conformance). Equivalent to `doc()->writer()`.

public writer() : PdfWriter
Return values
PdfWriter

writeTo()

public writeTo(resource $stream) : int
Parameters
$stream : resource
Return values
int

        
On this page

Search results