Symfony API reference
At a glance
Section titled “At a glance”The Symfony package exposes bundle registration, a configuration tree, an injectable factory for fresh documents, Hypertext Transfer Protocol (HTTP) response helpers, and Messenger types for asynchronous generation. Most application code uses only two symbols: the PdfFactory service you inject to build a Document, and the PdfResponse helper that turns that document into a secure HTTP response. The remaining symbols (bundle, extension, compiler pass, configuration tree, Messenger data transfer object (DTO), and handler) are wiring you configure once or that the framework manages for you.
Start here: Inject NextPDF\Symfony\Service\PdfFactory, call create() to get a fresh Document, and return it with NextPDF\Symfony\Http\PdfResponse::download(). The first sample shows that flow.
Common tasks
Section titled “Common tasks”Use these three runnable snippets for the most common tasks. Each snippet uses only the verified symbols documented in the tables that follow.
Return a Portable Document Format (PDF) download from a controller: inject the factory, build a document, and pass it to the response helper:
<?php
declare(strict_types=1);
namespace App\Controller;
use NextPDF\Symfony\Http\PdfResponse;use NextPDF\Symfony\Service\PdfFactory;use Symfony\Component\HttpFoundation\Response;use Symfony\Component\Routing\Attribute\Route;
final class InvoiceController{ #[Route('/invoice/{number}', name: 'invoice_pdf')] public function download(PdfFactory $pdf, string $number): Response { $doc = $pdf->create(); $doc->addPage(); $doc->setFont('dejavusans', '', 12); $doc->cell(0, 10, "Invoice #{$number}");
return PdfResponse::download($doc, "invoice-{$number}.pdf"); }}What it does: PdfFactory::create() returns a fresh, preconfigured Document. PdfResponse::download() sends it with Content-Type: application/pdf, an attachment disposition, and the bundle’s fixed security headers.
Stream a large PDF to keep peak memory low: use the streamed helper and return a StreamedResponse:
<?php
declare(strict_types=1);
namespace App\Controller;
use NextPDF\Symfony\Http\PdfResponse;use NextPDF\Symfony\Service\PdfFactory;use Symfony\Component\HttpFoundation\StreamedResponse;use Symfony\Component\Routing\Attribute\Route;
final class ReportController{ #[Route('/report', name: 'report_pdf')] public function report(PdfFactory $pdf): StreamedResponse { $doc = $pdf->create(); $doc->addPage(); $doc->setFont('dejavusans', '', 12); $doc->cell(0, 10, 'Annual report');
return PdfResponse::streamDownload($doc, 'annual-report.pdf'); }}What it does: PdfResponse::streamDownload() emits the materialized PDF in chunks and omits Content-Length; use streamInline() for the inline equivalent.
Dispatch a PDF for asynchronous generation: send a GeneratePdfMessage to a Messenger transport so rendering runs on a worker:
<?php
declare(strict_types=1);
namespace App\Controller;
use App\Pdf\InvoicePdfBuilder;use NextPDF\Symfony\Message\GeneratePdfMessage;use Symfony\Component\HttpFoundation\Response;use Symfony\Component\Messenger\MessageBusInterface;use Symfony\Component\Routing\Attribute\Route;
final class QueueController{ #[Route('/invoice/{id}/queue', name: 'invoice_queue')] public function queue(MessageBusInterface $bus, int $id): Response { $bus->dispatch(new GeneratePdfMessage( builderClass: InvoicePdfBuilder::class, outputPath: '/var/storage/invoices/' . $id . '.pdf', builderContext: ['invoice_id' => $id], ));
return new Response('PDF generation queued.', 202); }}What it does: the DTO carries a builder class-string and a validated output path. The handler resolves the builder, builds the document, and saves it on the worker. The builder class implements PdfBuilderInterface and is registered in a service locator (see the Symfony quickstart for the locator and worker wiring).
Factory
Section titled “Factory”Use this table for the exact constructor and create() contract of the injectable service that produces fresh documents.
| Symbol | Parameters | Default behavior | Returns | Throws or fails with | Notes |
|---|---|---|---|---|---|
new PdfFactory(DocumentFactoryInterface $factory, array $defaults, ?string $pdfa, array $artisanConfig) | factory: core factory; defaults: creator, author, language, margins; pdfa: optional PDF/A profile; artisanConfig: optional Chrome renderer config. | Defaults are applied only when configured. | PdfFactory | Container wiring errors. | The service can be singleton because create() returns a fresh document. |
PdfFactory::create() | none. | Applies creator and language; applies author only when non-empty; applies PDF/A and Artisan config only when available. | NextPDF\Core\Document | Core configuration errors. | Use once per request, command, or message. |
PdfFactory::setArtisanAvailable(bool $available) | available: compile-time availability flag. | Disabled until the compiler pass enables it. | void | none expected. | Internal hook called by the optional extension compiler pass. |
PdfFactory::setProAvailable(bool $available) | available: compile-time availability flag. | Disabled until the compiler pass enables it. | void | none expected. | Internal hook for Premium availability. |
Bundle, extension, and configuration
Section titled “Bundle, extension, and configuration”Use the first table for the wiring layer: bundle registration, the nextpdf config tree, and optional-extension detection. The second table lists the config keys.
| Symbol | Parameters | Default behavior | Returns | Throws or fails with | Notes |
|---|---|---|---|---|---|
NextPdfBundle::build(ContainerBuilder $container) | Symfony container builder. | Calls the parent build method and registers OptionalExtensionPass. | void | Compiler-pass registration errors. | Enables optional Artisan and Premium feature detection. |
NextPdfBundle::getPath() | none. | Returns the package root path. | string | none expected. | Used by Symfony bundle discovery and resource loading. |
NextPdfExtension::load(array $configs, ContainerBuilder $container) | User config arrays and container builder. | Processes nextpdf config, stores resolved parameters, loads service definitions, and checks required extensions. | void | Config validation, service load, or missing-extension errors. | Required extensions are mbstring and zlib. |
NextPdfExtension::getAlias() | none. | Uses nextpdf as the root config key. | string | none expected. | Configure the bundle under nextpdf:. |
Configuration::getConfigTreeBuilder() | none. | Defines the validated nextpdf configuration tree. | TreeBuilder | Symfony config-definition errors. | Mirrors the Laravel config shape where practical. |
OptionalExtensionPass::process(ContainerBuilder $container) | Symfony container builder. | Detects optional Artisan and Premium services and toggles factory availability flags. | void | Compiler-pass wiring errors. | Runs during container compilation. |
| Config key | Type | Default behavior | Notes |
|---|---|---|---|
page_format | enum | A4; allowed values include A3, A5, Letter, Legal, and Tabloid. | Applies to default document creation. |
orientation | enum | P; allowed values are P and L. | Use explicit document calls when a page needs a different orientation. |
unit | enum | mm; allowed values are pt, mm, cm, and in. | Keeps framework defaults aligned with core units. |
pdfa | `string | null` | null; allowed values are 4, 4e, and 4f. |
fonts_path / cache_path | string | Project fonts path and kernel cache path. | Keep each path readable or writable for its runtime role. |
signature.* | array | Disabled by default with signature level B-B. | Provides certificate, key, password, extra certificates, and level. |
tsa.* | array | Disabled when the Uniform Resource Locator (URL) is null; timeout defaults to 30 seconds. | Supports credentials, mutual Transport Layer Security (mTLS) files, public-key pins, and HTTP policy. |
ocsp_cache.* | array | Enabled with a time to live (TTL) of 86400 seconds. | Used by validation and long-term signature flows when available. |
messenger.* | array | Transport async, timeout 120, retries 3. | Used by asynchronous generation workflows. |
artisan.* | array | Chrome renderer is disabled unless configured and installed. | Maps to ChromeRendererConfig when the optional renderer is available. |
defaults.* | array | Creator NextPDF, author empty, language en, default margins and font. | Applied by PdfFactory::create(). |
HTTP responses
Section titled “HTTP responses”Use this table to choose a response helper by display mode and buffering: inline display or download, buffered or streamed. It also shows filename and header behavior.
| Symbol | Parameters | Default behavior | Returns | Throws or fails with | Notes |
|---|---|---|---|---|---|
PdfResponse::inline(Document $document, string $filename = 'document.pdf') | document: built document; filename: response filename. | Adds .pdf when missing. | Symfony\Component\HttpFoundation\Response | Core serialization errors. | Sets PDF content type and defensive headers. |
PdfResponse::download(Document $document, string $filename = 'document.pdf') | Same as inline; disposition is attachment. | Browser download response. | Response | Same as inline. | Use for explicit downloads. |
PdfResponse::streamInline(Document $document, string $filename = 'document.pdf') | Same as inline. | Emits the materialized PDF bytes in chunks. | StreamedResponse | Same as inline. | Does not avoid document materialization. |
PdfResponse::streamDownload(Document $document, string $filename = 'document.pdf') | Same as streamInline; disposition is attachment. | Download stream response. | StreamedResponse | Same as streamInline. | Apply output-size policy before render. |
Messenger
Section titled “Messenger”Use this table for the asynchronous path: the message DTO you dispatch, the builder interface you implement, and the handler that runs on the worker.
| Symbol | Parameters | Default behavior | Returns | Throws or fails with | Notes |
|---|---|---|---|---|---|
new GeneratePdfMessage(string $builderClass, string $outputPath, array $builderContext = []) | builderClass: class-string implementing PdfBuilderInterface; outputPath: target .pdf; builderContext: serializable data. | Empty context array. | Message DTO. | InvalidArgumentException for invalid fully qualified class name (FQCN), stream wrapper, null byte, traversal, empty path, or non-.pdf target. | Messenger transports carry data, not closures. |
PdfBuilderInterface::build(Document $document, array $context): Document | document: fresh configured document; context: serializable message data. | No default context beyond the message value. | Configured Document. | Builder-specific exceptions. | Make builders deterministic and idempotent. |
new GeneratePdfHandler(PdfFactory $pdfFactory, ContainerInterface $builderLocator) | PDF factory and tagged builder service locator. | No document is created during construction. | GeneratePdfHandler | Container wiring errors. | The locator should expose only PdfBuilderInterface implementations. |
GeneratePdfHandler::__invoke(GeneratePdfMessage $message) | message: validated message DTO. | Resolves the builder from the container, builds the document, and saves it. | void | Missing builder service, invalid builder result, core write errors. | Prefer service builders over static callbacks. |
Development notes
Section titled “Development notes”- Do not store a
Documentas a service. StorePdfFactoryand callcreate()for each unit of work. - Queue only serializable context. Do not put open streams, closures, or request objects into
builderContext. - Use an output path policy stricter than the DTO when the deployment has tenant-specific storage roots.