PdfWriter
in package
Ergonomic PDF document builder.
PdfWriter is the friendly facade: it owns a PdfFileWriter
under the hood and provides one method per "thing a user wants to
put in a document" — pages, fonts, content streams, images,
bookmarks, page labels, named destinations, signatures.
The byte-level file-assembly logic (header, xref, trailer,
signature patching) lives in PdfFileWriter in the core package.
Usage: $writer = new PdfWriter(); $page = $writer->addPage(612, 792); $font = $writer->addFont(new Type1Font(StandardFont::Helvetica)); $cs = $writer->addContentStream($page); $cs->beginText()->setFont('F1', 12)->moveTextPosition(72, 720)->showText('Hi')->endText(); $writer->save('/path/to/output.pdf');
Table of Contents
Methods
- __construct() : mixed
- addCompositeFont() : Font
- Build and register a Type 0 composite font from TrueType font data.
- addContentStream() : ContentStream
- Create a content stream, register it, and attach it to a page.
- addFont() : Font
- Register a font, auto-assign a resource name (F1, F2, …), and return the name.
- addImage() : string
- Add an image to a page as an XObject, using ImageParser to detect format.
- addOpenTypeFont() : Font
- Build and register an OpenType CFF composite font.
- addOutlineItem() : PdfReference
- addPage() : Page
- Add a new page. Accepts either a Rectangle (from phpdftk/geometry) or explicit width/height floats. Default is US Letter (612×792 pt).
- checkConformance() : array<int, ConformanceResult>
- Run conformance checks without generating the PDF.
- fileWriter() : PdfFileWriter
- Escape hatch to Level 0 — returns the underlying PdfFileWriter for direct object-model control.
- generate() : string
- Generate the complete PDF as a binary string.
- getCatalog() : Catalog
- getConformanceResults() : array<int, ConformanceResult>
- Get the conformance results from the last generate() call.
- getContentStreams() : array<int, ContentStream>
- Return all content streams added to the document.
- getEncodingWarnings() : array<int, string>
- Diagnostics for codepoints that were substituted with `?` because the font's encoding could not represent them. Empty when every glyph landed cleanly. Each entry names the font resource, the codepoint, and how many times it was requested.
- getFonts() : array<string, Font|Type0Font>
- Return all registered fonts, keyed by resource name.
- getPageTree() : PageTree
- getPdfVersion() : PdfVersion
- getVersionWarnings() : array<int, string>
- register() : PdfReference
- Register any arbitrary PdfObject (annotations, form fields, etc.).
- save() : void
- Write the PDF to a file, creating parent directories as needed.
- setCeilingVersion() : void
- setConformance() : void
- Set one or more conformance profiles (e.g. PDF/A-1b, PDF/UA-1).
- setConformanceProfiles() : void
- Set multiple conformance profiles at once (e.g. PDF/A-2a + PDF/UA-1).
- setDeprecationHandler() : void
- setEncryption() : void
- Configure encryption for the generated PDF.
- setInfo() : void
- setLinearized() : void
- Enable or disable linearized (web-optimized) PDF output.
- setMetadata() : void
- setNamedDestinations() : void
- setOutline() : Outline
- setPageLabels() : void
- setSigner() : void
- Configure digital signing for this document.
- setStrictDeprecation() : void
- setStrictVersionMode() : void
- setTimestamper() : void
- Configure a document-level timestamp using a TSA client.
- setTsaClient() : void
- Configure a TSA client for RFC 3161 timestamping.
- syncInfoToMetadata() : void
- toBytes() : string
- Alias for {@see generate()} — returns the raw PDF bytes as a string.
- writeTo() : int
- Write the generated PDF to an open stream resource.
Methods
__construct()
public
__construct([bool $compressStreams = true ][, PdfVersion|string $version = PdfFileWriter::DEFAULT_PDF_VERSION ]) : mixed
Parameters
- $compressStreams : bool = true
- $version : PdfVersion|string = PdfFileWriter::DEFAULT_PDF_VERSION
addCompositeFont()
Build and register a Type 0 composite font from TrueType font data.
public
addCompositeFont(TrueTypeData $data, array<string|int, int> $usedCodepoints[, Page|Page|null $page = null ]) : Font
Creates the full CID font stack: Type0Font -> CIDFontType2 -> FontDescriptor -> FontFile2, plus a ToUnicode CMap. The font is subset to include only the glyphs needed for the given codepoints.
Parameters
- $data : TrueTypeData
-
Parsed TrueType font data
- $usedCodepoints : array<string|int, int>
-
Unicode codepoints used in the document
- $page : Page|Page|null = null
-
If set, add font only to this page
Return values
Font —Opaque font handle
addContentStream()
Create a content stream, register it, and attach it to a page.
public
addContentStream(Page|Page $page) : ContentStream
Parameters
Return values
ContentStreamaddFont()
Register a font, auto-assign a resource name (F1, F2, …), and return the name.
public
addFont(Font $font[, Page|Page|null $page = null ]) : Font
The font is added to ALL existing pages' resources. For per-page fonts, add directly to page->resources.
Parameters
Return values
FontaddImage()
Add an image to a page as an XObject, using ImageParser to detect format.
public
addImage(string $path, Page|Page $page) : string
Returns the resource name (e.g. 'Im1') for use in content streams.
Parameters
Return values
stringaddOpenTypeFont()
Build and register an OpenType CFF composite font.
public
addOpenTypeFont(OpenTypeData $data, array<string|int, int> $usedCodepoints[, Page|Page|null $page = null ]) : Font
Creates the Type 0 → CIDFontType0 → FontDescriptor → CFFFontFile stack with a ToUnicode CMap for text extraction.
Parameters
- $data : OpenTypeData
-
Parsed OpenType font data
- $usedCodepoints : array<string|int, int>
-
Unicode codepoints used in the document
- $page : Page|Page|null = null
-
If set, add font only to this page
Return values
Font —Opaque font handle
addOutlineItem()
public
addOutlineItem(OutlineItem $item) : PdfReference
Use PdfDoc::addOutlineItem() instead. This forwarder is retained for one minor release.
Parameters
- $item : OutlineItem
Return values
PdfReferenceaddPage()
Add a new page. Accepts either a Rectangle (from phpdftk/geometry) or explicit width/height floats. Default is US Letter (612×792 pt).
public
addPage([Rectangle|float $widthOrRect = 612 ][, float $height = 792 ]) : Page
Parameters
- $widthOrRect : Rectangle|float = 612
- $height : float = 792
Return values
PagecheckConformance()
Run conformance checks without generating the PDF.
public
checkConformance() : array<int, ConformanceResult>
Return values
array<int, ConformanceResult>fileWriter()
Escape hatch to Level 0 — returns the underlying PdfFileWriter for direct object-model control.
public
fileWriter() : PdfFileWriter
Return values
PdfFileWritergenerate()
Generate the complete PDF as a binary string.
public
generate() : string
Return values
stringgetCatalog()
public
getCatalog() : Catalog
Return values
CataloggetConformanceResults()
Get the conformance results from the last generate() call.
public
getConformanceResults() : array<int, ConformanceResult>
Return values
array<int, ConformanceResult>getContentStreams()
Return all content streams added to the document.
public
getContentStreams() : array<int, ContentStream>
Return values
array<int, ContentStream>getEncodingWarnings()
Diagnostics for codepoints that were substituted with `?` because the font's encoding could not represent them. Empty when every glyph landed cleanly. Each entry names the font resource, the codepoint, and how many times it was requested.
public
getEncodingWarnings() : array<int, string>
Return values
array<int, string>getFonts()
Return all registered fonts, keyed by resource name.
public
getFonts() : array<string, Font|Type0Font>
Return values
array<string, Font|Type0Font>getPageTree()
public
getPageTree() : PageTree
Return values
PageTreegetPdfVersion()
public
getPdfVersion() : PdfVersion
Return values
PdfVersiongetVersionWarnings()
public
getVersionWarnings() : array<int, string>
Return values
array<int, string>register()
Register any arbitrary PdfObject (annotations, form fields, etc.).
public
register(PdfObject $object) : PdfReference
Parameters
- $object : PdfObject
Return values
PdfReferencesave()
Write the PDF to a file, creating parent directories as needed.
public
save(string $path) : void
Parameters
- $path : string
setCeilingVersion()
public
setCeilingVersion(PdfVersion|null $ceiling) : void
Parameters
- $ceiling : PdfVersion|null
setConformance()
Set one or more conformance profiles (e.g. PDF/A-1b, PDF/UA-1).
public
setConformance(ConformanceProfile $profile[, bool $strict = true ]) : void
When set, generate() will:
- Auto-inject XMP identification metadata (if not already present)
- Pin the PDF version to the profile minimum
- Run all applicable constraint checks
- In strict mode (default): throw ConformanceException on errors
- In lenient mode: collect results in getConformanceResults()
Parameters
- $profile : ConformanceProfile
- $strict : bool = true
-
Throw on conformance errors (default true)
setConformanceProfiles()
Set multiple conformance profiles at once (e.g. PDF/A-2a + PDF/UA-1).
public
setConformanceProfiles(array<string|int, ConformanceProfile> $profiles[, bool $strict = true ]) : void
Parameters
- $profiles : array<string|int, ConformanceProfile>
- $strict : bool = true
-
Throw on conformance errors (default true)
setDeprecationHandler()
public
setDeprecationHandler(Closure $handler) : void
Parameters
- $handler : Closure
setEncryption()
Configure encryption for the generated PDF.
public
setEncryption(PdfEncryptor $encryptor) : void
Registers the encrypt dictionary, and during generation all strings and streams are encrypted per-object with the correct key derivation. The /Encrypt reference is added to the trailer automatically.
Parameters
- $encryptor : PdfEncryptor
Tags
setInfo()
public
setInfo(Info $info) : void
Use PdfDoc::setInfo() instead. This forwarder is retained for one minor release and will be removed.
Parameters
- $info : Info
setLinearized()
Enable or disable linearized (web-optimized) PDF output.
public
setLinearized([bool $linearized = true ]) : void
When enabled, the generated PDF places the first page's objects at the front of the file, allowing a viewer to display it before downloading the rest (ISO 32000-2 Annex F).
Parameters
- $linearized : bool = true
setMetadata()
public
setMetadata(string $xmpXml) : void
Use PdfDoc::setMetadata() instead. This forwarder is retained for one minor release.
Parameters
- $xmpXml : string
setNamedDestinations()
public
setNamedDestinations(array<string, Destination> $destinations) : void
Use PdfDoc::setNamedDestinations() instead. This forwarder is retained for one minor release.
Parameters
- $destinations : array<string, Destination>
setOutline()
public
setOutline(Outline $outline) : Outline
Use PdfDoc::setOutline() instead. This forwarder is retained for one minor release and will be removed.
Parameters
- $outline : Outline
Return values
OutlinesetPageLabels()
public
setPageLabels(array<int, PageLabel> $labels) : void
Use PdfDoc::setPageLabels() instead. This forwarder is retained for one minor release.
Parameters
- $labels : array<int, PageLabel>
setSigner()
Configure digital signing for this document.
public
setSigner(SignatureValue $signatureValue, Pkcs7Signer $signer[, int $placeholderBytes = 8192 ]) : void
The signing lifecycle works in three phases:
- Placeholder: A SignatureValue dictionary is emitted with a
zeroed /Contents hex string large enough to hold the final
PKCS#7 DER blob (
$placeholderBytescontrols the size). - Byte-range: After the full PDF is assembled, the /ByteRange array is patched to cover everything except the /Contents value itself, so the signature covers the entire file.
- Patch: The Pkcs7Signer signs the byte-range data and the resulting DER is written into the /Contents placeholder.
Parameters
- $signatureValue : SignatureValue
- $signer : Pkcs7Signer
- $placeholderBytes : int = 8192
Tags
setStrictDeprecation()
public
setStrictDeprecation([bool $strict = true ]) : void
Parameters
- $strict : bool = true
setStrictVersionMode()
public
setStrictVersionMode([bool $strict = true ]) : void
Parameters
- $strict : bool = true
setTimestamper()
Configure a document-level timestamp using a TSA client.
public
setTimestamper(SignatureValue $docTimeStamp, TsaClient $tsaClient[, int $placeholderBytes = 16384 ]) : void
Parameters
- $docTimeStamp : SignatureValue
- $tsaClient : TsaClient
- $placeholderBytes : int = 16384
Tags
setTsaClient()
Configure a TSA client for RFC 3161 timestamping.
public
setTsaClient(TsaClient $tsaClient) : void
Parameters
- $tsaClient : TsaClient
Tags
syncInfoToMetadata()
public
syncInfoToMetadata() : void
Use PdfDoc::syncInfoToMetadata() instead. This forwarder is retained for one minor release.
toBytes()
Alias for {@see generate()} — returns the raw PDF bytes as a string.
public
toBytes() : string
Return values
stringwriteTo()
Write the generated PDF to an open stream resource.
public
writeTo(resource $stream) : int
Parameters
- $stream : resource