### Install laravel-pdf Package Source: https://spatie.be/docs/laravel-pdf/v2/installation-setup Install the main package using Composer. ```bash composer require spatie/laravel-pdf ``` -------------------------------- ### Install WeasyPrint PHP Wrapper Source: https://spatie.be/docs/laravel-pdf/v2/drivers/using-the-weasyprint-driver Install the PHP wrapper package for WeasyPrint using Composer. ```bash composer require pontedilana/php-weasyprint ``` -------------------------------- ### Install Chrome Package Source: https://spatie.be/docs/laravel-pdf/v2/drivers/using-the-chrome-driver Install the necessary Chrome package using Composer. ```bash composer require chrome-php/chrome ``` -------------------------------- ### Install DOMPDF Package Source: https://spatie.be/docs/laravel-pdf/v2/drivers/using-the-dompdf-driver Install the dompdf/dompdf package using Composer. ```bash composer require dompdf/dompdf ``` -------------------------------- ### WeasyPrint Driver Configuration Options Source: https://spatie.be/docs/laravel-pdf/v2/drivers/using-the-weasyprint-driver Example of WeasyPrint driver configuration in `config/laravel-pdf.php`, including binary path and timeout. ```php 'weasyprint' => [ 'binary' => env('LARAVEL_PDF_WEASYPRINT_BINARY', 'weasyprint'), 'timeout' => 10, ], ``` -------------------------------- ### Install Browsershot Driver Source: https://spatie.be/docs/laravel-pdf/v2/installation-setup Install the Browsershot driver dependency using Composer. Ensure you also meet Browsershot's system requirements. ```bash composer require spatie/browsershot ``` -------------------------------- ### Start Gotenberg Instance with Docker Source: https://spatie.be/docs/laravel-pdf/v2/drivers/using-the-gotenberg-driver Run a Gotenberg instance locally using Docker. Ensure the port is exposed for the Laravel application to connect. ```bash docker run --rm -p 3000:3000 gotenberg/gotenberg:8 ``` -------------------------------- ### Register Laravel Boost Skill Source: https://spatie.be/docs/laravel-pdf/v2/installation-setup Run this Artisan command after installing the package to register the Laravel Boost skill for AI agents. ```bash php artisan boost:install ``` -------------------------------- ### Assert Browsershot Configuration Source: https://spatie.be/docs/laravel-pdf/v2/basic-usage/testing-pdfs Use `assertBrowsershot` to verify customizations made to the underlying Browsershot instance via `withBrowsershot`, without needing to start Chrome. ```php use Spatie\Browsershot\Browsershot; use Spatie\LaravelPdf\Facades\Pdf; Pdf::view('invoice') ->withBrowsershot(function (Browsershot $browsershot) { $browsershot->setRemoteInstance('127.0.0.1', 9222); }) ->save('invoice.pdf'); Pdf::assertBrowsershot(function (Browsershot $browsershot) { return invade($browsershot)->additionalOptions['remoteInstanceUrl'] === 'http://127.0.0.1:9222'; }); ``` -------------------------------- ### Per-PDF Browsershot Customization with Scale Source: https://spatie.be/docs/laravel-pdf/v2/drivers/customizing-browsershot Customize the Browsershot instance for an individual PDF by calling the `withBrowsershot` method with a closure. This example scales the PDF output. ```php use Spatie\LaravelPdf\Facades\Pdf; use Spatie\Browsershot\Browsershot; Pdf::view('test') ->withBrowsershot(function (Browsershot $browsershot) { $browsershot->scale(0.5); }) ->save($this->targetPath); ``` -------------------------------- ### Example Footer View with Directives Source: https://spatie.be/docs/laravel-pdf/v2/basic-usage/formatting-pdfs An example of a footer view. The @pageNumber and @totalPages directives are supported by Browsershot, Cloudflare, and Chrome drivers but not by DOMPDF. ```html footer { font-size: 12px; } This is the footer ``` -------------------------------- ### Save PDF to a Specific Disk Source: https://spatie.be/docs/laravel-pdf/v2/basic-usage/saving-pdfs-to-disks Use the `disk()` method to specify which configured Laravel filesystem disk to save the PDF to. This example saves to the 's3' disk. ```php use Spatie\LaravelPdf\Facades\Pdf; Pdf::view('invoice') ->disk('s3') ->save('invoice-april-2022.pdf'); ``` -------------------------------- ### Add Gotenberg to docker-compose.yml Source: https://spatie.be/docs/laravel-pdf/v2/drivers/using-the-gotenberg-driver Integrate Gotenberg into your Docker Compose setup for easier management. This defines the service and its port mapping. ```yaml services: gotenberg: image: gotenberg/gotenberg:8 ports: - "3000:3000" ``` -------------------------------- ### Gotenberg Header/Footer HTML Structure Source: https://spatie.be/docs/laravel-pdf/v2/drivers/using-the-gotenberg-driver Example HTML structure for headers and footers in Gotenberg. It includes basic styling and placeholders for dynamic content like page numbers. ```html

Page of

``` ```html A good match? ``` -------------------------------- ### Generate PDF on AWS Lambda Source: https://spatie.be/docs/laravel-pdf/v2/drivers/generating-pdfs-on-aws-lambda Use this snippet to generate a PDF using a Blade view and save it to a file on AWS Lambda. Ensure you have installed hammerstone/sidecar and wnx/sidecar-browsershot. ```php use Spatie\Pdf\Facades\Pdf; Pdf::view('pdf.invoice', $data) ->onLambda() ->save('invoice.pdf'); ``` -------------------------------- ### Create PDF from Blade View with Data Source: https://spatie.be/docs/laravel-pdf/v2/basic-usage/creating-pdfs Pass data to a Blade view when generating a PDF. This allows you to dynamically populate the PDF content, for example, with an Eloquent model like an invoice. ```php use Spatie\LaravelPdf\Facades\Pdf; Pdf::view('pdf.invoice', ['invoice' => $invoice]) ->save('/some/directory/invoice.pdf'); ``` -------------------------------- ### Return PDF Inline Source: https://spatie.be/docs/laravel-pdf/v2/basic-usage/responding-with-pdfs Use the `pdf()` helper to create a PDF from a view and return it. The PDF will be inlined in the browser by default and named upon download. ```php use function Spatie\LaravelPdf\Support\pdf; class DownloadInvoiceController { public function __invoke(Invoice $invoice) { return pdf() ->view('pdf.invoice', compact('invoice')) ->name('invoice-2023-04-10.pdf'); } } ``` -------------------------------- ### Basic Queued PDF Generation Source: https://spatie.be/docs/laravel-pdf/v2/basic-usage/queued-pdf-generation Dispatch PDF generation to a background queue. This renders the HTML, dispatches a job, and saves the PDF to the specified path. ```php use Spatie\LaravelPdf\Facades\Pdf; Pdf::view('pdfs.invoice', ['invoice' => $invoice]) ->format('a4') ->saveQueued('invoice.pdf'); ``` -------------------------------- ### Configure Gotenberg Driver Source: https://spatie.be/docs/laravel-pdf/v2/installation-setup Add these lines to your .env file to use the Gotenberg driver. Ensure you have a running Gotenberg instance. ```dotenv LARAVEL_PDF_DRIVER=gotenberg GOTENBERG_URL=http://your-host:your-port # If you set up authentication, add these lines too: GOTENBERG_USERNAME=username GOTENBERG_PASSWORD=password ``` -------------------------------- ### Set Default PDF Options Source: https://spatie.be/docs/laravel-pdf/v2/basic-usage/setting-defaults Configure default header and format for all generated PDFs. This should typically be done in a service provider's boot method. ```php use Spatie\LaravelPdf\Facades\Pdf; use Spatie\LaravelPdf\Enums\Format; // in a service provider Pdf::default() ->headerView('pdf.header') ->format(Format::A3); ``` -------------------------------- ### Queued PDF Generation with Callbacks Source: https://spatie.be/docs/laravel-pdf/v2/basic-usage/queued-pdf-generation Add `then()` and `catch()` callbacks to react to the success or failure of a queued PDF generation job. The `then` callback receives the saved path and disk name. ```php Pdf::view('pdfs.invoice', ['invoice' => $invoice]) ->saveQueued('invoice.pdf') ->then(fn (string $path, ?string $diskName) => Mail::to($user)->send(new InvoiceMail($path))) ->catch(fn (Throwable $e) => Log::error('PDF generation failed', ['error' => $e->getMessage()])); ``` ```php ->then(function (string $path, ?string $diskName) { $contents = $diskName ? Storage::disk($diskName)->get($path) : file_get_contents($path); }) ``` -------------------------------- ### Gotenberg Driver Configuration Source: https://spatie.be/docs/laravel-pdf/v2/drivers/configuration Configure the URL for the Gotenberg API. Defaults to 'http://localhost:3000' if GOTENBERG_URL is not set. ```php 'gotenberg' => [ 'url' => env('GOTENBERG_URL', 'http://localhost:3000'), ], ``` -------------------------------- ### Configure Chrome Binary Path in .env Source: https://spatie.be/docs/laravel-pdf/v2/drivers/using-the-chrome-driver If Chrome cannot be auto-discovered, specify the path to the Chrome/Chromium executable in your .env file. ```dotenv LARAVEL_PDF_CHROME_BINARY=/usr/bin/google-chrome-stable ``` -------------------------------- ### Select PDF Driver Source: https://spatie.be/docs/laravel-pdf/v2/drivers/configuration Configure the default PDF generation driver using the LARAVEL_PDF_DRIVER environment variable. Defaults to 'browsershot'. ```php 'driver' => env('LARAVEL_PDF_DRIVER', 'browsershot'), ``` -------------------------------- ### Browsershot Driver Configuration Source: https://spatie.be/docs/laravel-pdf/v2/drivers/configuration Configure paths and options for the Browsershot driver, including Node.js, npm, and Chrome binaries. Use environment variables for dynamic settings. ```php 'browsershot' => [ 'node_binary' => env('LARAVEL_PDF_NODE_BINARY'), 'npm_binary' => env('LARAVEL_PDF_NPM_BINARY'), 'include_path' => env('LARAVEL_PDF_INCLUDE_PATH'), 'chrome_path' => env('LARAVEL_PDF_CHROME_PATH'), 'node_modules_path' => env('LARAVEL_PDF_NODE_MODULES_PATH'), 'bin_path' => env('LARAVEL_PDF_BIN_PATH'), 'temp_path' => env('LARAVEL_PDF_TEMP_PATH'), 'write_options_to_file' => env('LARAVEL_PDF_WRITE_OPTIONS_TO_FILE', false), 'no_sandbox' => env('LARAVEL_PDF_NO_SANDBOX', false), ], ``` -------------------------------- ### Runtime Driver Switching Source: https://spatie.be/docs/laravel-pdf/v2/drivers/configuration Switch between PDF drivers on a per-PDF basis using the `driver` method. You can specify a driver like 'cloudflare' or rely on the default configured driver. ```php use Spatie\LaravelPdf\Facades\Pdf; // Use the Cloudflare driver for this specific PDF Pdf::view('invoice', $data) ->driver('cloudflare') ->save('invoice.pdf'); // Use the default driver from config Pdf::view('invoice', $data) ->save('invoice.pdf'); ``` -------------------------------- ### Set PDF Metadata Source: https://spatie.be/docs/laravel-pdf/v2/basic-usage/formatting-pdfs Set the PDF title and creation date using the `meta` method. This works with all drivers. ```php use Spatie\LaravelPdf\Facades\Pdf; Pdf::view('pdf.invoice', ['invoice' => $invoice]) ->meta(title: 'Invoice #123', creationDate: now()) ->save('/some/directory/invoice.pdf'); ``` -------------------------------- ### Switch to Cloudflare Driver for Specific PDFs Source: https://spatie.be/docs/laravel-pdf/v2/drivers/using-the-cloudflare-driver Use the `driver('cloudflare')` method to generate specific PDFs using the Cloudflare driver, even if it's not your default. ```php use Spatie\LaravelPdf\Facades\Pdf; Pdf::view('pdfs.invoice', ['invoice' => $invoice]) ->driver('cloudflare') ->format('a4') ->save('invoice.pdf'); ``` -------------------------------- ### Configure Chrome Driver Options Source: https://spatie.be/docs/laravel-pdf/v2/drivers/using-the-chrome-driver Customize Chrome driver settings like binary path, sandbox, timeouts, and custom flags within the 'config/laravel-pdf.php' file. ```php 'chrome' => [ 'chrome_binary' => env('LARAVEL_PDF_CHROME_BINARY'), 'no_sandbox' => env('LARAVEL_PDF_CHROME_NO_SANDBOX', false), 'startup_timeout' => env('LARAVEL_PDF_CHROME_STARTUP_TIMEOUT', 30), 'timeout' => env('LARAVEL_PDF_CHROME_TIMEOUT', 30000), 'operation_timeout' => env('LARAVEL_PDF_CHROME_OPERATION_TIMEOUT', 5000), 'user_data_dir' => env('LARAVEL_PDF_CHROME_USER_DATA_DIR'), 'custom_flags' => [], 'env_variables' => [], ] ``` -------------------------------- ### Publish Laravel PDF Configuration Source: https://spatie.be/docs/laravel-pdf/v2/drivers/configuration Run this Artisan command to publish the configuration file to your application's config directory. ```bash php artisan vendor:publish --tag=pdf-config ``` -------------------------------- ### Chrome Driver Configuration Source: https://spatie.be/docs/laravel-pdf/v2/drivers/configuration Configure options for the Chrome driver, including the binary path, sandbox settings, and timeouts. Custom flags and environment variables can also be specified. ```php 'chrome' => [ 'chrome_binary' => env('LARAVEL_PDF_CHROME_BINARY'), 'no_sandbox' => env('LARAVEL_PDF_CHROME_NO_SANDBOX', false), 'startup_timeout' => env('LARAVEL_PDF_CHROME_STARTUP_TIMEOUT', 30), 'timeout' => env('LARAVEL_PDF_CHROME_TIMEOUT', 30000), 'operation_timeout' => env('LARAVEL_PDF_CHROME_OPERATION_TIMEOUT', 5000), 'user_data_dir' => env('LARAVEL_PDF_CHROME_USER_DATA_DIR'), 'custom_flags' => [], 'env_variables' => [], ], ``` -------------------------------- ### Cloudflare Driver Configuration Source: https://spatie.be/docs/laravel-pdf/v2/drivers/configuration Configure API credentials for the Cloudflare Browser Rendering API. Ensure CLOUDFLARE_API_TOKEN and CLOUDFLARE_ACCOUNT_ID are set. ```php 'cloudflare' => [ 'api_token' => env('CLOUDFLARE_API_TOKEN'), 'account_id' => env('CLOUDFLARE_ACCOUNT_ID'), ], ``` -------------------------------- ### Queue Configuration for Queued PDF Generation Source: https://spatie.be/docs/laravel-pdf/v2/basic-usage/queued-pdf-generation Specify the connection and queue name directly or use chained methods for full control over the queued job, proxied to Laravel's `PendingDispatch`. ```php Pdf::view('pdfs.invoice', $data) ->saveQueued('invoice.pdf', connection: 'redis', queue: 'pdfs'); ``` ```php Pdf::view('pdfs.invoice', $data) ->saveQueued('invoice.pdf') ->onQueue('pdfs') ->onConnection('redis') ->delay(now()->addMinutes(5)); ``` -------------------------------- ### Set Page Margins Source: https://spatie.be/docs/laravel-pdf/v2/basic-usage/formatting-pdfs Configure page margins using the `margins` method. Millimeters are the default unit, but custom units can be specified. ```php use Spatie\LaravelPdf\Facades\Pdf; Pdf::view('pdf.invoice', ['invoice' => $invoice]) ->margins($top, $right, $bottom, $left) ->save('/some/directory/invoice-april-2022.pdf'); ``` -------------------------------- ### Assert PDF Response Download Source: https://spatie.be/docs/laravel-pdf/v2/basic-usage/testing-pdfs Use `assertRespondedWithPdf` to check if a route generated and returned a PDF as a download. You can also assert properties of the PDF content. ```php use Spatie\LaravelPdf\Facades\Pdf; use Spatie\LaravelPdf\PdfBuilder; it('can download an invoice', function () { $this ->get('download-invoice') ->assertOk(); Pdf::assertRespondedWithPdf(function (PdfBuilder $pdf) { return $pdf->downloadName === 'invoice-for-april-2022.pdf' && $pdf->isDownload() && str_contains($pdf->html, 'Your total for April is $10.00'); }); }); ``` -------------------------------- ### Specify WeasyPrint Driver for Specific PDFs Source: https://spatie.be/docs/laravel-pdf/v2/drivers/using-the-weasyprint-driver Use the `driver` method to switch to the WeasyPrint driver for generating a specific PDF, even if it's not the default. ```php use Spatie\LaravelPdf\Facades\Pdf; Pdf::view('pdfs.invoice', ['invoice' => $invoice]) ->driver('weasyprint') ->format('a4') ->save('invoice.pdf'); ``` -------------------------------- ### Use Custom Macro with PdfBuilder Source: https://spatie.be/docs/laravel-pdf/v2/advanced-usage/extending-with-macros Utilize the previously defined 'withCustomHeader' macro when building a PDF. This demonstrates how to chain custom methods for specific PDF configurations. ```php use Spatie\LaravelPdf\Facades\Pdf; Pdf::view('invoice') ->withCustomHeader('Invoice #123') ->save('invoice.pdf'); ``` -------------------------------- ### Assert PDF Queued by Path Source: https://spatie.be/docs/laravel-pdf/v2/basic-usage/testing-pdfs Use `assertQueued` with a string path to verify that a PDF generation job has been queued for the specified file. ```php Pdf::assertQueued('invoice.pdf'); ``` -------------------------------- ### Use Chrome Driver for Specific PDFs Source: https://spatie.be/docs/laravel-pdf/v2/drivers/using-the-chrome-driver Switch to the Chrome driver for generating a particular PDF, while keeping another driver as the default. ```php use Spatie\LaravelPdf\Facades\Pdf; Pdf::view('pdfs.invoice', ['invoice' => $invoice]) ->driver('chrome') ->format('a4') ->save('invoice.pdf'); ``` -------------------------------- ### Configure Chrome Driver in .env Source: https://spatie.be/docs/laravel-pdf/v2/drivers/using-the-chrome-driver Set the default PDF driver to 'chrome' in your .env file. ```dotenv LARAVEL_PDF_DRIVER=chrome ``` -------------------------------- ### Controller for Downloading Invoice PDF Source: https://spatie.be/docs/laravel-pdf/v2/advanced-usage/using-tailwind This controller demonstrates how to use the laravel-pdf package to generate and download a PDF from a Blade view. It passes dynamic data to the view. ```php namespace App\Http\Controllers; use function Spatie\LaravelPdf\Support\pdf; class DownloadInvoiceController { public function __invoke() { return pdf('pdf.invoice', [ 'invoiceNumber' => '1234', 'customerName' => 'Grumpy Cat', ]); } } ``` -------------------------------- ### Test PDF Generation Source: https://spatie.be/docs/laravel-pdf/v2 Uses the `Pdf::fake()` to mock PDF generation during tests. Assert that the PDF was responded with and optionally check its content. ```php use Spatie\LaravelPdf\Facades\Pdf; it('can render an invoice', function () { Pdf::fake(); $invoice = Invoice::factory()->create(); $this->get(route('download-invoice', $invoice)) ->assertOk(); Pdf::assertRespondedWithPdf(function (PdfBuilder $pdf) { return $pdf->contains('test'); }); }); ``` -------------------------------- ### Assert PDF View Source: https://spatie.be/docs/laravel-pdf/v2/basic-usage/testing-pdfs Use `assertViewIs` to verify that a PDF was generated using a specific Blade view. ```php Pdf::assertViewIs('pdf.invoice'); ``` -------------------------------- ### Default Laravel PDF Configuration Source: https://spatie.be/docs/laravel-pdf/v2/installation-setup This is the content of the published configuration file, showing default driver and driver-specific settings. ```php return [ 'driver' => env('LARAVEL_PDF_DRIVER', 'browsershot'), 'browsershot' => [ 'node_binary' => env('LARAVEL_PDF_NODE_BINARY'), 'npm_binary' => env('LARAVEL_PDF_NPM_BINARY'), 'include_path' => env('LARAVEL_PDF_INCLUDE_PATH'), 'chrome_path' => env('LARAVEL_PDF_CHROME_PATH'), 'node_modules_path' => env('LARAVEL_PDF_NODE_MODULES_PATH'), 'bin_path' => env('LARAVEL_PDF_BIN_PATH'), 'temp_path' => env('LARAVEL_PDF_TEMP_PATH'), 'write_options_to_file' => env('LARAVEL_PDF_WRITE_OPTIONS_TO_FILE', false), 'no_sandbox' => env('LARAVEL_PDF_NO_SANDBOX', false), ], 'cloudflare' => [ 'api_token' => env('CLOUDFLARE_API_TOKEN'), 'account_id' => env('CLOUDFLARE_ACCOUNT_ID'), ], 'dompdf' => [ 'is_remote_enabled' => env('LARAVEL_PDF_DOMPDF_REMOTE_ENABLED', false), 'chroot' => env('LARAVEL_PDF_DOMPDF_CHROOT'), ], 'weasyprint' => [ 'binary' => env('LARAVEL_PDF_WEASYPRINT_BINARY', 'weasyprint'), 'timeout' => 10, ], 'chrome' => [ 'chrome_binary' => env('LARAVEL_PDF_CHROME_BINARY'), 'no_sandbox' => env('LARAVEL_PDF_CHROME_NO_SANDBOX', false), 'startup_timeout' => env('LARAVEL_PDF_CHROME_STARTUP_TIMEOUT', 30), 'timeout' => env('LARAVEL_PDF_CHROME_TIMEOUT', 30000), 'operation_timeout' => env('LARAVEL_PDF_CHROME_OPERATION_TIMEOUT', 5000), 'user_data_dir' => env('LARAVEL_PDF_CHROME_USER_DATA_DIR'), 'custom_flags' => [], 'env_variables' => [], ], ]; ``` -------------------------------- ### Return PDF as Controller Response Source: https://spatie.be/docs/laravel-pdf/v2 Generates a PDF from a Blade view and returns it as a downloadable response from a controller. Use this to directly serve PDFs to users. ```php use Spatie\LaravelPdf\Facades\Pdf; class DownloadInvoiceController { public function __invoke(Invoice $invoice) { return Pdf::view('pdfs.invoice', ['invoice' => $invoice]) ->format('a4') ->name('your-invoice.pdf'); } } ``` -------------------------------- ### Generate PDF Using Defaults Source: https://spatie.be/docs/laravel-pdf/v2/basic-usage/setting-defaults This PDF will use the default A3 format set previously. No explicit format is specified here. ```php // this PDF will use the defaults: it will be rendered in A3 format Pdf::html('Hello world') ->save('my-a3-pdf.pdf') ``` -------------------------------- ### Configure Cloudflare Driver in .env Source: https://spatie.be/docs/laravel-pdf/v2/drivers/using-the-cloudflare-driver Add these environment variables to your .env file to enable the Cloudflare driver for PDF generation. ```env LARAVEL_PDF_DRIVER=cloudflare CLOUDFLARE_API_TOKEN=your-api-token CLOUDFLARE_ACCOUNT_ID=your-account-id ``` -------------------------------- ### Generate PDF using Cloudflare Driver Source: https://spatie.be/docs/laravel-pdf/v2/drivers/using-the-cloudflare-driver This code snippet demonstrates how to generate a PDF using the Cloudflare driver. No code changes are needed if Cloudflare is set as the default driver in your environment. ```php use Spatie\LaravelPdf\Facades\Pdf; // This will use Cloudflare — no code changes needed Pdf::view('pdfs.invoice', ['invoice' => $invoice]) ->format('a4') ->save('invoice.pdf'); ``` -------------------------------- ### Implement PdfDriver Interface Source: https://spatie.be/docs/laravel-pdf/v2/drivers/custom-drivers A custom driver must implement the Spatie\LaravelPdf\Drivers\PdfDriver interface, providing methods for PDF generation and saving. The PdfOptions object contains formatting details. ```php namespace App\Pdf\Drivers; use Spatie\LaravelPdf\Drivers\PdfDriver; use Spatie\LaravelPdf\PdfOptions; class WeasyPrintDriver implements PdfDriver { public function __construct(protected array $config = []) { } public function generatePdf( string $html, ?string $headerHtml, ?string $footerHtml, PdfOptions $options, ): string { // Generate and return the PDF content as a string } public function savePdf( string $html, ?string $headerHtml, ?string $footerHtml, PdfOptions $options, string $path, ): void { // Generate the PDF and save it to the given path } } ``` -------------------------------- ### Setting Transparent Background with Browsershot Source: https://spatie.be/docs/laravel-pdf/v2/basic-usage/formatting-pdfs Configure the Browsershot driver to render a transparent background for the PDF. This is useful when the PDF is intended to be overlaid on other content. ```php use Spatie\LaravelPdf\Facades\Pdf; use Spatie\Browsershot\Browsershot; Pdf::view('test') ->withBrowsershot(function (Browsershot $browsershot) { $browsershot->transparentBackground(); }) ->save($this->targetPath); ``` -------------------------------- ### Generate PDF using Gotenberg Driver Source: https://spatie.be/docs/laravel-pdf/v2/drivers/using-the-gotenberg-driver Use the Pdf facade to generate a PDF from a Blade view. The driver will automatically use Gotenberg for the conversion process. ```php use Spatie\LaravelPdf\Facades\Pdf; Pdf::view('pdfs.invoice', ['invoice' => $invoice]) ->format('a4') ->save('invoice.pdf'); ``` -------------------------------- ### Configure WeasyPrint Driver in .env Source: https://spatie.be/docs/laravel-pdf/v2/drivers/using-the-weasyprint-driver Set the default PDF driver to 'weasyprint' in your Laravel application's .env file. ```dotenv LARAVEL_PDF_DRIVER=weasyprint ``` -------------------------------- ### Fake PDF Generation in Tests Source: https://spatie.be/docs/laravel-pdf/v2/basic-usage/testing-pdfs In your tests, call `Pdf::fake()` to mock PDF generation, significantly speeding up test execution. This should typically be done in a `beforeEach` hook. ```php use Spatie\LaravelPdf\Facades\Pdf; beforeEach(function () { Pdf::fake(); }); ``` -------------------------------- ### Assert PDF Content Multiple Strings Source: https://spatie.be/docs/laravel-pdf/v2/basic-usage/testing-pdfs Pass an array of strings to `assertSee` to ensure all specified strings are present within the generated PDF content. ```php Pdf::assertSee([ 'Your total for April is $10.00', 'Your total for May is $20.00', ]); ``` -------------------------------- ### Queue PDF Generation Source: https://spatie.be/docs/laravel-pdf/v2 Generates a PDF in the background using Laravel's queue system. This is useful for long-running PDF generation tasks to avoid blocking web requests. It allows chaining actions like sending an email after generation. ```php use Spatie\LaravelPdf\Facades\Pdf; Pdf::view('pdfs.invoice', ['invoice' => $invoice]) ->format('a4') ->saveQueued('invoice.pdf') ->then(fn (string $path, ?string $diskName) => Mail::to($user)->send(new InvoiceMail($path))); ``` -------------------------------- ### Assert PDF Metadata Source: https://spatie.be/docs/laravel-pdf/v2/basic-usage/testing-pdfs Verify that a PDF was generated with specific metadata by inspecting the `metadata` property on the `PdfBuilder` instance within an assertion. ```php use Spatie\LaravelPdf\Facades\Pdf; use Spatie\LaravelPdf\PdfBuilder; Pdf::assertSaved(function (PdfBuilder $pdf) { return $pdf->metadata->title === 'Invoice #123' && $pdf->metadata->author === 'Acme Corp'; }); ``` -------------------------------- ### Assert No PDFs Queued Source: https://spatie.be/docs/laravel-pdf/v2/basic-usage/testing-pdfs Use `assertNotQueued` without arguments to assert that no PDF generation jobs are currently queued. ```php // Assert nothing was queued Pdf::assertNotQueued(); ``` -------------------------------- ### Conditional Formatting with 'when' Source: https://spatie.be/docs/laravel-pdf/v2/basic-usage/formatting-pdfs Conditionally apply formatting options like landscape or header views based on specific conditions using the `when` method. This allows for dynamic PDF generation. ```php use Spatie\LaravelPdf\Facades\Pdf; Pdf::view('pdf.invoice', ['invoice' => $invoice]) ->format('a4') ->when($invoice->isLandscape(), fn ($pdf) => $pdf->landscape()) ->when($invoice->hasLetterhead(), function ($pdf) use ($invoice) { $pdf->headerView('pdf.letterhead', ['company' => $invoice->company]); }) ->save('/some/directory/invoice.pdf'); ``` -------------------------------- ### Testing Queued PDF Generation Source: https://spatie.be/docs/laravel-pdf/v2/basic-usage/queued-pdf-generation Use `Pdf::fake()` to mock PDF generation and assert that PDFs were queued using methods like `assertQueued()`, `assertNotQueued()`, or with custom callable assertions. ```php use Spatie\LaravelPdf\Facades\Pdf; use Spatie\LaravelPdf\PdfBuilder; Pdf::fake(); // ... your code that queues a PDF ... Pdf::assertQueued('invoice.pdf'); // Or use a callable for more detailed assertions: Pdf::assertQueued(function (PdfBuilder $pdf, string $path) { return $path === 'invoice.pdf' && $pdf->contains('Total'); }); // Assert nothing was queued: Pdf::assertNotQueued(); // Assert a specific path was not queued: Pdf::assertNotQueued('other.pdf'); ``` -------------------------------- ### Saving Queued PDF to a Specific Disk Source: https://spatie.be/docs/laravel-pdf/v2/basic-usage/queued-pdf-generation Configure the queued job to save the PDF to a specified disk, such as 's3', and access its URL in a `then` callback. ```php Pdf::view('pdfs.invoice', $data) ->disk('s3') ->saveQueued('invoices/invoice.pdf') ->then(function (string $path, ?string $diskName) { $url = Storage::disk($diskName)->url($path); // ... }); ``` -------------------------------- ### Use Registered Custom PDF Driver Source: https://spatie.be/docs/laravel-pdf/v2/drivers/custom-drivers Utilize the registered custom driver for generating and saving PDFs on a per-PDF basis by specifying the driver name. ```php use Spatie\LaravelPdf\Facades\Pdf; Pdf::view('pdfs.invoice', ['invoice' => $invoice]) ->driver('weasyprint') ->save('invoice.pdf'); ``` -------------------------------- ### Create PDF from HTML String Source: https://spatie.be/docs/laravel-pdf/v2/basic-usage/creating-pdfs Generate a PDF directly from a string of HTML content. This is useful for simple, dynamically generated HTML that doesn't require a full Blade view. ```php use Spatie\LaravelPdf\Facades\Pdf; Pdf::html('Hello world!!')->save('/some/directory/invoice.pdf'); ``` -------------------------------- ### Save PDF from Blade View Source: https://spatie.be/docs/laravel-pdf/v2 Renders a Blade view with provided data and saves it as a PDF file. Ensure the Blade view and data are correctly set up. ```php use Spatie\LaravelPdf\Facades\Pdf; Pdf::view('pdfs.invoice', ['invoice' => $invoice]) ->format('a4') ->save('invoice.pdf') ``` -------------------------------- ### Register Custom PDF Driver Source: https://spatie.be/docs/laravel-pdf/v2/drivers/custom-drivers Register your custom PDF driver as a singleton in a Laravel service provider, typically aliasing it for specific use. ```php namespace App\Providers; use App\Pdf\Drivers\WeasyPrintDriver; use Illuminate\Support\ServiceProvider; class PdfServiceProvider extends ServiceProvider { public function register(): void { $this->app->singleton('laravel-pdf.driver.weasyprint', function () { return new WeasyPrintDriver(config('laravel-pdf.weasyprint', [])); }); } } ``` -------------------------------- ### Debugging PDF Builder State Source: https://spatie.be/docs/laravel-pdf/v2/basic-usage/formatting-pdfs Inspect the current state of the PDF builder by calling `dump` on the builder instance. This method dumps the state and continues the chain, useful for debugging. ```php use Spatie\LaravelPdf\Facades\Pdf; Pdf::view('pdf.invoice', ['invoice' => $invoice]) ->format('a4') ->landscape() ->dump() // dumps the builder state and continues ->save('/some/directory/invoice.pdf'); ``` -------------------------------- ### Assert PDF View Has Data Key Source: https://spatie.be/docs/laravel-pdf/v2/basic-usage/testing-pdfs Use `assertViewHas` to confirm that a specific key was passed to the PDF's view data. This helps verify data availability. ```php Pdf::assertViewHas('invoice'); ``` -------------------------------- ### Configure DOMPDF Driver Options Source: https://spatie.be/docs/laravel-pdf/v2/drivers/using-the-dompdf-driver Customize DOMPDF driver settings such as remote resource fetching and chroot path in the Laravel configuration file. ```php 'dompdf' => [ 'is_remote_enabled' => env('LARAVEL_PDF_DOMPDF_REMOTE_ENABLED', false), 'chroot' => env('LARAVEL_PDF_DOMPDF_CHROOT'), ], ``` -------------------------------- ### Assert PDF Queued with Callable Source: https://spatie.be/docs/laravel-pdf/v2/basic-usage/testing-pdfs Use `assertQueued` with a callable for more detailed assertions on the queued PDF job, checking both the path and content. ```php use Spatie\LaravelPdf\PdfBuilder; Pdf::assertQueued(function (PdfBuilder $pdf, string $path) { return $path === 'invoice.pdf' && $pdf->contains('Total'); }); ``` -------------------------------- ### Create PDF from Blade View Source: https://spatie.be/docs/laravel-pdf/v2/basic-usage/creating-pdfs Generate a PDF from a Blade view and save it to a specified directory. This is the most common way to create PDFs in a Laravel application. ```php use Spatie\LaravelPdf\Facades\Pdf; Pdf::view('pdf.invoice')->save('/some/directory/invoice.pdf'); ``` -------------------------------- ### Force PDF Download Source: https://spatie.be/docs/laravel-pdf/v2/basic-usage/responding-with-pdfs To ensure the PDF is always downloaded by the user, chain the `download()` method after setting the view and name. ```php use function Spatie\LaravelPdf\Support\pdf; class DownloadInvoiceController { public function __invoke(Invoice $invoice) { return pdf() ->view('pdf.invoice', compact('invoice')) ->name('invoice-2023-04-10.pdf') ->download(); } } ``` -------------------------------- ### Use DOMPDF for Specific PDFs Source: https://spatie.be/docs/laravel-pdf/v2/drivers/using-the-dompdf-driver Generate a specific PDF using the DOMPDF driver while maintaining a different default driver for the application. ```php use Spatie\LaravelPdf\Facades\Pdf; Pdf::view('pdfs.invoice', ['invoice' => $invoice]) ->driver('dompdf') ->format('a4') ->save('invoice.pdf'); ``` -------------------------------- ### Set PDF Header and Footer using Views Source: https://spatie.be/docs/laravel-pdf/v2/basic-usage/formatting-pdfs Use headerView and footerView methods to specify Blade views for the PDF header and footer. Ensure CSS is included within the header/footer views as they do not inherit from the main view. ```php use Spatie\LaravelPdf\Facades\Pdf; Pdf::view('pdf.invoice', ['invoice' => $invoice]) ->headerView('pdf.invoice.header') ->footerView('pdf.invoice.footer') ->save('/some/directory/invoice-april-2022.pdf'); ``` -------------------------------- ### Set PDF Header and Footer using HTML Source: https://spatie.be/docs/laravel-pdf/v2/basic-usage/formatting-pdfs Use headerHtml and footerHtml methods to directly set HTML content for the PDF header and footer. CSS must be included within the provided HTML strings. ```php use Spatie\LaravelPdf\Facades\Pdf; Pdf::view('pdf.invoice', ['invoice' => $invoice]) ->headerHtml('My header') ->footerHtml('My footer') ->save('/some/directory/invoice-april-2022.pdf'); ``` -------------------------------- ### Set PDF Metadata Source: https://spatie.be/docs/laravel-pdf/v2/basic-usage/formatting-pdfs Add document metadata like title, author, subject, and keywords using the `meta` method. This information is visible in PDF viewers. ```php use Spatie\LaravelPdf\Facades\Pdf; Pdf::view('pdf.invoice', ['invoice' => $invoice]) ->meta( title: 'Invoice #123', author: 'Acme Corp', subject: 'Monthly invoice', keywords: 'invoice, acme, april', creator: 'My Application', ); ``` -------------------------------- ### Set Page Margins with Custom Unit Source: https://spatie.be/docs/laravel-pdf/v2/basic-usage/formatting-pdfs Specify a custom unit for page margins using the `margins` method's fifth parameter, such as `Unit::Pixel`. ```php use Spatie\LaravelPdf\Facades\Pdf; use Spatie\LaravelPdf\Enums\Unit; Pdf::view('pdf.invoice', ['invoice' => $invoice]) ->margins($top, $right, $bottom, $left, Unit::Pixel) ->save('/some/directory/invoice-april-2022.pdf'); ``` -------------------------------- ### Simple PDF Assertion Methods Source: https://spatie.be/docs/laravel-pdf/v2/basic-usage/testing-pdfs Simple assertion methods are available to assert that a PDF was generated. These are suitable for code that generates a single PDF. If multiple PDFs are generated, use `assertSaved`. ```php use Spatie\LaravelPdf\Facades\Pdf; // Example of a simple assertion method (specific method not shown in source, but implied) // Pdf::assertGenerated(); ``` -------------------------------- ### Assert PDF View Has Data Key with Value Source: https://spatie.be/docs/laravel-pdf/v2/basic-usage/testing-pdfs Use `assertViewHas` with a second parameter to assert that a specific key was passed to the PDF's view data with an expected value. ```php Pdf::assertViewHas('invoice', $invoice); ``` -------------------------------- ### JavaScript Execution in PDF Generation Source: https://spatie.be/docs/laravel-pdf/v2/basic-usage/creating-pdfs Demonstrates how JavaScript in an HTML view is executed when using browser-based drivers (Browsershot, Cloudflare, Chrome). The DomPDF driver does not support JavaScript execution. ```html Test
``` ```php use Spatie\LaravelPdf\Facades\Pdf; Pdf::view('your-view')->save($pathToPdf); ``` -------------------------------- ### Configure Laravel for Gotenberg Driver Source: https://spatie.be/docs/laravel-pdf/v2/drivers/using-the-gotenberg-driver Set the Laravel PDF driver to 'gotenberg' and specify the Gotenberg service URL in your .env file. This enables the driver for PDF generation. ```dotenv LARAVEL_PDF_DRIVER=gotenberg GOTENBERG_URL=http://localhost:3000 ``` -------------------------------- ### Assert Specific PDF Not Queued Source: https://spatie.be/docs/laravel-pdf/v2/basic-usage/testing-pdfs Use `assertNotQueued` with a path to assert that a PDF for a specific file path has not been queued. ```php // Assert a specific path was not queued Pdf::assertNotQueued('other.pdf'); ``` -------------------------------- ### Assert PDF Saved to Path Source: https://spatie.be/docs/laravel-pdf/v2/basic-usage/testing-pdfs Use `assertSaved` to verify that a PDF file has been successfully saved to a specified storage path. ```php Pdf::assertSaved(storage_path('invoices/invoice.pdf')); ``` -------------------------------- ### Set AWS Lambda as Default PDF Generator Source: https://spatie.be/docs/laravel-pdf/v2/drivers/generating-pdfs-on-aws-lambda Configure your application to use AWS Lambda for all PDF generations by default. This is typically done within a service provider. ```php // typically, in a service provider use Spatie\Pdf\Facades\Pdf; Pdf::default()->onLambda(); ``` -------------------------------- ### Set Custom PDF Driver as Default Source: https://spatie.be/docs/laravel-pdf/v2/drivers/custom-drivers To make your custom driver the default, bind it to the PdfDriver interface in your service provider's registration method. ```php use App\Pdf\Drivers\WeasyPrintDriver; use Spatie\LaravelPdf\Drivers\PdfDriver; $this->app->singleton(PdfDriver::class, function () { return new WeasyPrintDriver(config('laravel-pdf.weasyprint', [])); }); ``` -------------------------------- ### Generating a PDF with a Custom Footer and Page Numbers Source: https://spatie.be/docs/laravel-pdf/v2/advanced-usage/creating-pdfs-with-multiple-pages This PHP code snippet shows how to generate a PDF using a main view and a separate footer view that includes page numbering directives (@pageNumber and @totalPages). Ensure you are using a compatible driver (Browsershot, Cloudflare, or Chrome) for the page numbering to function correctly. ```php use Spatie\LaravelPdf\Facades\Pdf; Pdf::view('view-with-multiple-pages')->footerView('footer-view')->save($path); ``` -------------------------------- ### Set Custom Paper Size Source: https://spatie.be/docs/laravel-pdf/v2/basic-usage/formatting-pdfs Define a custom paper size for the PDF using the `paperSize` method, specifying width, height, and unit (e.g., 'mm'). ```php use Spatie\LaravelPdf\Facades\Pdf; Pdf::view('pdf.receipt', ['order' => $order]) ->paperSize(57, 500, 'mm') ->save('/some/directory/receipt-12345.pdf'); ``` -------------------------------- ### Assert PDF Saved with Specific Properties Source: https://spatie.be/docs/laravel-pdf/v2/basic-usage/testing-pdfs Use `assertSaved` to verify that a PDF was saved with expected properties. Pass a callable that receives a `PdfBuilder` instance and returns `true` if the assertion should pass. ```php use Spatie\LaravelPdf\Facades\Pdf; use Spatie\LaravelPdf\PdfBuilder; Pdf::assertSaved(function (PdfBuilder $pdf) { return $pdf->downloadName === 'invoice.pdf' && str_contains($pdf->html, 'Your total for April is $10.00'); }); ``` -------------------------------- ### Customizing the Queued PDF Job Class Source: https://spatie.be/docs/laravel-pdf/v2/basic-usage/queued-pdf-generation Replace the default job class used by `saveQueued()` by extending the default job and configuring it in `config/laravel-pdf.php`. This allows setting defaults like retry attempts and timeouts. ```php 'job' => \App\Jobs\GeneratePdfJob::class, ``` ```php namespace App\Jobs; use Spatie\LaravelPdf\Jobs\GeneratePdfJob as BaseJob; class GeneratePdfJob extends BaseJob { public int $tries = 3; public int $timeout = 120; public int $backoff = 30; } ``` -------------------------------- ### Set DOMPDF Driver in .env Source: https://spatie.be/docs/laravel-pdf/v2/drivers/using-the-dompdf-driver Configure your Laravel application to use the DOMPDF driver by setting the LARAVEL_PDF_DRIVER environment variable. ```env LARAVEL_PDF_DRIVER=dompdf ```