Skip to content

Laravel API reference

The nextpdf/laravel package connects the framework-independent NextPDF core to a Laravel application. You call four entry points directly: the Pdf facade for short authoring flows, the PdfDocumentInterface container binding for injectable document creation, the PdfResponse helper for HTTP responses from completed documents, and the GeneratePdfJob queue job for off-request generation. The NextPdfServiceProvider registers each binding and is auto-discovered, so you do not need manual setup. Configuration in config/nextpdf.php controls defaults, fonts, queues, and optional signing and time-stamp authority (TSA) features.

Start here: to send a Portable Document Format (PDF) file directly from a controller, build a document and return PdfResponse::download($document, 'file.pdf'). The first example below shows this flow.

The snippets below cover the three flows you will usually use first. Each snippet is verified against the package source; complete per-symbol tables follow.

Return a downloadable PDF from a controller. This is the most common task:

<?php
declare(strict_types=1);
namespace App\Http\Controllers;
use Illuminate\Http\Response;
use NextPDF\Contracts\PdfDocumentInterface;
use NextPDF\Laravel\Http\PdfResponse;
final class ReportController extends Controller
{
public function download(PdfDocumentInterface $document): Response
{
$document->addPage();
$document->cell(0, 10, 'Monthly report', newLine: true);
return PdfResponse::download($document, 'report.pdf');
}
}

What it does: injects a fresh document, writes one line, and returns an attachment response with Content-Type: application/pdf and the Open Worldwide Application Security Project (OWASP) security headers. Use inline() instead of download() to preview in the browser.

Author and save with the Pdf facade. This is the shortest path for scripts and short flows:

<?php
declare(strict_types=1);
use NextPDF\Laravel\Facades\Pdf;
Pdf::addPage();
Pdf::cell(0, 10, 'Hello from Laravel', newLine: true);
Pdf::save(storage_path('app/hello.pdf'));

What it does: the facade resolves a fresh document from the container, writes one cell, and saves the completed PDF to disk.

Generate a PDF off the request thread with GeneratePdfJob:

<?php
declare(strict_types=1);
use NextPDF\Contracts\PdfDocumentInterface;
use NextPDF\Laravel\Jobs\GeneratePdfJob;
GeneratePdfJob::dispatch(
storage_path('app/reports/january-2026.pdf'),
static fn (PdfDocumentInterface $document): PdfDocumentInterface => $document
->addPage()
->cell(0, 10, 'January report', newLine: true),
);

What it does: queues generation on a worker. The builder closure receives a container-resolved document and returns it. The job validates the .pdf output path before saving. Queue name, timeout, and connection come from config('nextpdf.queue.*').

The Pdf facade statically proxies a fresh core Document. Use it in short controller flows when the static style is clear. Each row lists one proxied document method.

SymbolParametersDefault behaviorReturnsThrows or fails withNotes
NextPDF\Laravel\Facades\Pdfnone; the static facade accessor resolves NextPDF\Contracts\PdfDocumentInterfaceLaravel resolves the current container binding for the document interface.The underlying core document fluent API.Laravel container binding failure if the provider is not registered.Use it for short controller flows. Prefer constructor injection for services and jobs.
Pdf::setTitle(string $title)title: document title.Replaces any existing title.staticCore validation or write-time errors.Proxies to the core Document.
Pdf::setAuthor(string $author)author: document author metadata.Replaces any previous author.staticCore metadata validation errors.Prefer configured defaults for application-wide metadata.
Pdf::addPage(?PageSize $size = null, Orientation $orientation = Portrait)size: optional page size; orientation: Portrait by default.Uses configured or default page size when size is omitted.staticCore page validation errors.Use explicit PageSize when output size matters.
Pdf::setFont(string $family, string $style = '', float $size = 12.0)Font family, style, and point size.Uses empty style and 12 pt size.staticFont registry or encoding errors.Preload production fonts through nextpdf.preload_fonts when latency matters.
Pdf::cell(float $width, float $height, string $text = '', bool $border = false, bool $newLine = false, Alignment $align = Left)Cell box, text, border flag, line-break flag, and alignment.Uses empty text, no border, no line break, and left alignment.staticLayout or text encoding errors.Use for simple fixed-layout output.
Pdf::multiCell(float $width, float $height, string $text, bool $border = false, Alignment $align = Left)Cell width, line height, text, border flag, alignment.No border and left alignment.staticLayout or text encoding errors.Use when text should wrap within a fixed width.
Pdf::writeHtml(string $html)html: HTML fragment.Renders on the current page and creates one when needed.staticCore HTML rendering errors.Apply input size and resource policies before accepting untrusted HTML.
Pdf::image(string $file, ?float $x = null, ?float $y = null, ?float $width = null, ?float $height = null)File path and optional placement rectangle.Lets the core document choose the current position and intrinsic size when coordinates are omitted.staticImage decode, path, or layout errors.Validate image source policy before accepting user-provided paths.
Pdf::output(?string $filename = null, OutputDestination $dest = Inline)filename: optional name; dest: output destination.Outputs inline when destination is omitted.stringCore serialization errors.Prefer PdfResponse for Laravel HTTP responses.
Pdf::save(string $path)path: filesystem target.Writes the completed PDF to disk.voidFilesystem or core write errors.Validate output directories in application code.
Pdf::getPdfData()none.Materializes PDF bytes in memory.stringCore serialization errors.Use when another framework object must own the response body.

Use this table when you need to resolve or override a container entry directly, such as injecting DocumentFactoryInterface into a service or checking what provides() defers.

SymbolParametersDefault behaviorReturnsThrows or fails withNotes
NextPdfServiceProvider::register()none.Merges config/nextpdf.php; registers registries, document factory, document binding, HTTP client, TSA client, signer, and optional e-invoice contracts.voidContainer or optional class resolution errors when a feature is used.FontRegistryInterface and ImageRegistry are shared; documents are always fresh.
NextPdfServiceProvider::boot()none.Validates required PHP extensions and publishes nextpdf-config in console mode.voidRuntimeException if a required extension is unavailable.Required extensions are mbstring and zlib.
NextPdfServiceProvider::provides()none.Reports deferred service IDs.array<string>none expected.Includes PdfDocumentInterface, DocumentFactoryInterface, FontRegistryInterface, SignerInterface, TsaClient, ClientInterface, and nextpdf.
PdfDocumentInterface / nextpdfresolved from the Laravel container.Creates a disposable Document through DocumentFactoryInterface, then applies configured defaults and optional PDF/A or Artisan settings.NextPDF\Core\DocumentOptional extension errors when configured but unavailable.Resolve a new document for each request or job.
DocumentFactoryInterfaceresolved from the Laravel container.Singleton factory that shares the process-lifetime font and image registries.DocumentFactoryInterfaceRegistry setup errors.Use this for explicit dependency injection.
SignerInterfaceresolved from the Laravel container.Returns null unless nextpdf.signature.enabled is set and certificate paths are configured.`SignerInterfacenull`Certificate load or signature-level validation errors.

Use this table to look up runtime-facing nextpdf.* keys read by the bindings. The full per-key reference, including environment variables and defaults, is at /integrations/laravel/configuration/.

KeyTypeDefault behaviorNotes
nextpdf.fonts_pathstringUses Laravel resource fonts when omitted.Directory for custom fonts and warmup.
nextpdf.cache_pathstringApplication cache path.Keep it writable by the PHP worker.
nextpdf.preload_fontslist<string>Empty list.Warmed during registry creation, then the registry is locked.
nextpdf.image_cache_mbintBounded image cache size.Limits process-lifetime image cache memory.
nextpdf.defaults.*arrayCreator NextPDF, language en, optional author and layout defaults.Applied to each fresh document.
nextpdf.artisan.*arrayChrome renderer disabled unless installed and configured.Maps to ChromeRendererConfig::fromArray().
nextpdf.signature.*arraySigning disabled by default.Certificate, private key, password, extra certificates, and signature level.
nextpdf.tsa.*arrayTSA disabled when the Uniform Resource Locator (URL) is empty.Supports credentials, mutual Transport Layer Security (mTLS) files, timeout, public-key pins, and HTTP policy.
nextpdf.ocsp_cache.*arrayOnline Certificate Status Protocol (OCSP) cache enabled with configured TTL.Used by signature validation flows when available.

Use this table when you return a completed document over HTTP and need to choose inline display, attachment download, or streamed output.

SymbolParametersDefault behaviorReturnsThrows or fails withNotes
PdfResponse::inline(Document $document, string $filename = 'document.pdf')document: built document; filename: Content-Disposition filename.Normalizes empty filenames to document.pdf.Illuminate\Http\ResponseCore serialization or response construction errors.Sets PDF content type and defensive headers.
PdfResponse::download(Document $document, string $filename = 'document.pdf')Same as inline; disposition is attachment.Returns a browser download response.Illuminate\Http\ResponseSame as inline.Use for explicit file downloads.
PdfResponse::streamInline(Document $document, string $filename = 'document.pdf')Same as inline.Materializes PDF bytes, then emits 64 KB chunks.Symfony\Component\HttpFoundation\StreamedResponseSame as inline.This is streamed HTTP output, not zero-copy rendering.
PdfResponse::streamDownload(Document $document, string $filename = 'document.pdf')Same as streamInline; disposition is attachment.Download stream response.StreamedResponseSame as streamInline.Enforce input and output size limits before rendering.

Use this table when you move generation off the request thread. It covers construction, dispatch, and success or failure callbacks for GeneratePdfJob.

SymbolParametersDefault behaviorReturnsThrows or fails withNotes
new GeneratePdfJob(string $outputPath, callable $builder, ?callable $onSuccess = null, ?callable $onFailure = null)outputPath: target .pdf; builder: receives a PdfDocumentInterface; callbacks are optional.Queue name, timeout, and connection are read from config('nextpdf.queue.*').Job instance.Serialization errors if the builder or callbacks cannot be serialized.The builder must return the configured document.
GeneratePdfJob::handle()none.Resolves PdfDocumentInterface, applies the builder, validates the output path, then saves.voidInvalidArgumentException for unsafe output paths; core write errors.Rejects stream wrappers, null bytes, .. segments, and non-.pdf paths.
GeneratePdfJob::failed(Throwable $exception)exception: failure cause.Calls the configured failure callback when present.voidCallback failures.Keep callbacks idempotent.
GeneratePdfJob::then(callable $callback)callback: receives the output path.Replaces the success callback.selfSerializable-closure errors.Fluent helper for dispatch setup.
GeneratePdfJob::catch(callable $callback)callback: receives the thrown Throwable.Replaces the failure callback.selfSerializable-closure errors.Use for alerting or compensating cleanup.
  • PdfResponse always calls getPdfData() before it constructs a response. It is not a lazy document builder.
  • Queue payloads can be tampered with in shared transports; keep output paths confined to an application-owned directory.
  • Use a fresh document per request or job. Do not reuse a document across requests.