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 filetoBytes(): string— get the bytes as a stringwriteTo($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
__construct()
public
__construct([PageSize $pageSize = PageSize::Letter ][, Theme|null $theme = null ][, bool $compressStreams = true ]) : mixed
Parameters
- $pageSize : PageSize = PageSize::Letter
- $theme : Theme|null = null
- $compressStreams : bool = true
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
selfaddCallout()
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
selfaddHeading()
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
selfaddHtml()
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
selfaddImage()
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
selfaddList()
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
Return values
selfaddNumberedList()
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
Return values
selfaddPage()
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
selfaddQuote()
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
selfaddRule()
Add a horizontal rule spanning the current content column.
public
addRule([float $lineWidth = 0.5 ]) : self
Parameters
- $lineWidth : float = 0.5
Return values
selfaddSpacer()
Add vertical whitespace (points).
public
addSpacer(float $points) : self
Parameters
- $points : float
Return values
selfaddTable()
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
selfaddText()
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
selfattachFile()
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
selfdoc()
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
PdfDocenableOutline()
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
selfgetEncodingWarnings()
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>getPdfVersion()
public
getPdfVersion() : PdfVersion
Return values
PdfVersiongetTheme()
public
getTheme() : Theme
Return values
ThemenewPage()
Force a page break. Equivalent to `addPage()` with the current size.
public
newPage() : self
Return values
selfsave()
public
save(string $path) : void
Parameters
- $path : string
setAuthor()
public
setAuthor(string $author) : self
Parameters
- $author : string
Return values
selfsetColumns()
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
selfsetCreator()
public
setCreator(string $creator) : self
Parameters
- $creator : string
Return values
selfsetFont()
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
selfsetFooter()
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
selfsetHeader()
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
selfsetKeywords()
public
setKeywords(string $keywords) : self
Parameters
- $keywords : string
Return values
selfsetOpenAction()
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
selfsetSubject()
public
setSubject(string $subject) : self
Parameters
- $subject : string
Return values
selfsetTheme()
public
setTheme(Theme $theme) : self
Parameters
- $theme : Theme
Return values
selfsetTitle()
public
setTitle(string $title) : self
Parameters
- $title : string
Return values
selfsetViewerPreferences()
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
selfsetWatermark()
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
selfshowPageNumbers()
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
selftoBytes()
public
toBytes() : string
Return values
stringwriter()
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
PdfWriterwriteTo()
public
writeTo(resource $stream) : int
Parameters
- $stream : resource