### Generate and return PDF in Laravel controller Source: https://spatie.be/docs/laravel-pdf/v1/basic-usage/responding-with-pdfs Creates a PDF response using a Blade view and returns it to be displayed in the browser. The PDF will be inlined by default. Requires the Spatie Laravel-pdf package and a corresponding Blade view template. The example shows generating an invoice PDF. ```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'); } } ``` -------------------------------- ### Return PDF as Response in Laravel Controller Source: https://spatie.be/docs/laravel-pdf/v1/introduction This code example shows how to return a generated PDF as a response from a Laravel controller method. It uses the Spatie Laravel PDF package to create a PDF from a Blade view and sets a specific filename for the download. This is useful for direct user downloads of generated documents. ```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'); } } ``` -------------------------------- ### Publish Laravel PDF Config File in Shell Source: https://spatie.be/docs/laravel-pdf/v1/advanced-usage/configuration Executes PHP Artisan command to publish the Laravel PDF configuration file to the app. Requires Laravel framework installation. Input: shell command. Output: copies config/laravel-pdf.php to app config directory. No known limitations. ```shell php artisan vendor:publish --tag=laravel-pdf-config ``` -------------------------------- ### Configure PDF Defaults in Laravel Service Provider Source: https://spatie.be/docs/laravel-pdf/v1/basic-usage/setting-defaults Shows how to set global default options for PDF generation using the Pdf facade in a service provider's boot method. These defaults apply to all PDFs but can be overridden when generating individual documents. The example configures a default header view and A3 format. ```php use Spatie\LaravelPdf\Facades\Pdf; use Spatie\LaravelPdf\Enums\Format; // in a service provider Pdf::default() ->headerView('pdf.header') ->format(Format::A3); ``` ```php // this PDF will use the defaults: it will be rendered in A3 format Pdf::html('

Hello world

') ->save('my-a3-pdf.pdf') // here we override the default: this PDF will be rendered in A4 format Pdf::html('

Hello world

') ->format(Format::A4) ->save('my-a4-pdf.pdf') ``` -------------------------------- ### Set AWS Lambda as Default for PDF Generation in Spatie Laravel-pdf Source: https://spatie.be/docs/laravel-pdf/v1/advanced-usage/generating-pdfs-on-aws-lambda Configure `spatie/laravel-pdf` to use AWS Lambda for all PDF generation by default. This is typically done within a service provider. This setup ensures all subsequent PDF generation calls will be processed on Lambda, provided the necessary `hammerstone/sidecar` and `wnx/sidecar-browsershot` packages are installed and configured. ```php // typically, in a service provider Pdf::default()->onLambda(); ``` -------------------------------- ### Fake PDF Generation for Faster Tests in Laravel Source: https://spatie.be/docs/laravel-pdf/v1/basic-usage/testing-pdfs This snippet demonstrates how to fake the PDF generation process in your Laravel tests using the Pdf facade. Faking the generation significantly speeds up your test execution by avoiding actual PDF rendering. It requires the spatie/laravel-pdf package and is typically set up in a `beforeEach` block in your test files. ```php use Spatie\LaravelPdf\Facades\Pdf; beforeEach(function () { Pdf::fake(); }); ``` -------------------------------- ### Set Transparent Background for PDF using Browsershot (PHP) Source: https://spatie.be/docs/laravel-pdf/v1/basic-usage/formatting-pdfs This PHP code demonstrates how to configure Browsershot, used by spatie/laravel-pdf, to generate a PDF with a transparent background. The `transparentBackground()` method is called on the Browsershot instance, which is passed to the `withBrowsershot` closure within the PDF generation process. This is useful when overlaying PDF content on other backgrounds. ```php Pdf::view('test') ->withBrowsershot(function (Browsershot $browsershot) { $browsershot->transparentBackground(); }) ->save($this->targetPath); ``` -------------------------------- ### Return PDF Response from Laravel Controller Source: https://spatie.be/docs/laravel-pdf/v1/index This code returns a downloadable PDF response from a controller invoke method. It uses the Pdf facade to render a Blade view with data and sets the filename. Dependencies include the Laravel PDF package; inputs are route parameters like an invoice model, output is an HTTP response with the PDF attachment. ```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'); } } ``` -------------------------------- ### PDF Generation with JavaScript Execution Source: https://spatie.be/docs/laravel-pdf/v1/basic-usage/creating-pdfs Demonstrates how JavaScript embedded in HTML is executed during PDF creation. This allows for dynamic content rendering, such as charts generated by JavaScript libraries. The PDF is generated from a view. ```php use Spatie\LaravelPdf\Facades\Pdf; Pdf::view('your-view')->save($pathToPdf); ``` -------------------------------- ### Test PDF Rendering in Laravel Source: https://spatie.be/docs/laravel-pdf/v1/index This test case fakes PDF generation to verify invoice rendering without creating files. It uses Pdf::fake() and assertions on the response. Dependencies include the Laravel PDF package and a factory for the Invoice model; it checks for specific content in the PDF builder, useful for unit tests but limited to mocked outputs. ```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'); }); }); ``` -------------------------------- ### Generate and Save PDF in Laravel Source: https://spatie.be/docs/laravel-pdf/v1/index This snippet generates a PDF from a Blade view using the Pdf facade and saves it to a file. It depends on the Spatie\LaravelPdf package and Browsershot for rendering. Inputs include the view path and data like an invoice object; output is a local PDF file with specified format like A4. ```php use Spatie\LaravelPdf\Facades\Pdf; Pdf::view('pdfs.invoice', ['invoice' => $invoice]) ->format('a4') ->save('invoice.pdf') ``` -------------------------------- ### Simple PDF Assertion Methods in Laravel Source: https://spatie.be/docs/laravel-pdf/v1/basic-usage/testing-pdfs These simple assertion methods (`assertViewIs`, `assertSee`, `assertViewHas`) are designed for testing code that generates a single PDF. They pass if any generated PDF matches the assertion criteria. For scenarios with multiple PDFs, `assertSaved` is recommended. These methods are part of the spatie/laravel-pdf package. ```php use Spatie\LaravelPdf\Facades\Pdf; Pdf::assertViewIs('pdf.invoice'); ``` ```php use Spatie\LaravelPdf\Facades\Pdf; Pdf::assertSee('Your total for April is $10.00'); ``` ```php use Spatie\LaravelPdf\Facades\Pdf; Pdf::assertSee([ 'Your total for April is $10.00', 'Your total for May is $20.00', ]); ``` ```php use Spatie\LaravelPdf\Facades\Pdf; Pdf::assertViewHas('invoice'); ``` ```php use Spatie\LaravelPdf\Facades\Pdf; Pdf::assertViewHas('invoice', $invoice); ``` -------------------------------- ### Create PDF from Blade View Source: https://spatie.be/docs/laravel-pdf/v1/basic-usage/creating-pdfs Generates a PDF document from a specified Blade view file. The PDF is saved to a given directory path. This method is suitable for dynamic content generation within Laravel. ```php use Spatie\LaravelPdf\Facades\Pdf; Pdf::view('pdf.invoice')->save('/some/directory/invoice.pdf'); ``` -------------------------------- ### Force PDF download in Laravel controller Source: https://spatie.be/docs/laravel-pdf/v1/basic-usage/responding-with-pdfs Creates a PDF response and forces it to be downloaded by the browser rather than displayed inline. Uses the download() method to change the response behavior. Requires the Spatie Laravel-pdf package and a corresponding Blade view template. ```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(); } } ``` -------------------------------- ### Generate PDF on AWS Lambda with Spatie Laravel-pdf Source: https://spatie.be/docs/laravel-pdf/v1/advanced-usage/generating-pdfs-on-aws-lambda This code snippet demonstrates how to generate a PDF from a Blade view using the `spatie/laravel-pdf` package and deploy the generation process to AWS Lambda. It requires the `hammerstone/sidecar` and `wnx/sidecar-browsershot` packages. ```php Pdf::view('pdf.invoice', $data) ->onLambda() ->save('invoice.pdf'); ``` -------------------------------- ### Create PDF from HTML String Source: https://spatie.be/docs/laravel-pdf/v1/basic-usage/creating-pdfs Generates a PDF document directly from an HTML string. This is useful for simple, static PDF content or when HTML is generated programmatically without using Blade views. ```php use Spatie\LaravelPdf\Facades\Pdf; Pdf::html('

Hello world!!

')->save('/some/directory/invoice.pdf'); ``` -------------------------------- ### Create PDF from Blade View with Data Source: https://spatie.be/docs/laravel-pdf/v1/basic-usage/creating-pdfs Generates a PDF from a Blade view, passing an array of data to be used within the view. This allows for dynamic population of the PDF content, such as passing an Eloquent model. ```php use Spatie\LaravelPdf\Facades\Pdf; Pdf::view('pdf.invoice', ['invoice' => $invoice]) ->save('/some/directory/invoice.pdf'); ``` -------------------------------- ### Global Browsershot Configuration in Laravel PDF AppServiceProvider Source: https://spatie.be/docs/laravel-pdf/v1/advanced-usage/customizing-browsershot This code binds a custom PdfFactory in the AppServiceProvider's boot method to apply global Browsershot options, such as Chrome args for disabling web security. It depends on the Spatie LaravelPdf package and affects all PDFs application-wide. Inputs are the args array for setOption; no direct outputs, but enables local asset access; limitation is it applies universally without per-PDF overrides. ```PHP use Spatie\LaravelPdf\PdfFactory; class AppServiceProvider extends ServiceProvider { //... /** * Bootstrap any application services. */ public function boot(): void { app()->bind(PdfFactory::class, function ($service, $app) { return (new PdfFactory())->withBrowsershot( function ($browserShot) { $browserShot->setOption( 'args', [ '--disable-web-security', '--allow-file-access-from-files', ], ); } ); }); } } ``` -------------------------------- ### Laravel Controller for PDF Generation Source: https://spatie.be/docs/laravel-pdf/v1/advanced-usage/using-tailwind A PHP controller that utilizes the Spatie Laravel PDF package to generate and download a PDF. It takes a Blade view name and an array of data to pass 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', ]); } } ``` -------------------------------- ### Save PDF to configured disk using Laravel PDF (PHP) Source: https://spatie.be/docs/laravel-pdf/v1/basic-usage/saving-pdfs-to-disks Demonstrates saving a generated PDF to a specific filesystem disk (e.g., S3) with the Spatie Laravel PDF package. Requires the Pdf facade and a disk configured in config/filesystems.php. The code creates a PDF from a view and stores it at the given path on the chosen disk. ```php use Spatie\\LaravelPdf\\Facades\\Pdf;\n\nPdf::view('invoice')\n ->disk('s3')\n ->save('invoice-april-2022.pdf'); ``` -------------------------------- ### Configure Browsershot Options in PHP Source: https://spatie.be/docs/laravel-pdf/v1/advanced-usage/configuration Defines a PHP array for Browsershot configuration options including paths to binaries like Node, NPM, Chrome. Used in config/laravel-pdf.php. Inputs: environment variables or direct values. Outputs: configured Browsershot settings for PDF generation. Can be overridden per instance. ```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), ], ``` -------------------------------- ### Test PDF Generation with Spatie Laravel PDF Source: https://spatie.be/docs/laravel-pdf/v1/introduction This snippet illustrates how to test PDF generation within a Laravel application using the Spatie Laravel PDF package's testing utilities. It includes faking the PDF facade, making a request that should trigger PDF generation, and asserting that the PDF was responded with, optionally checking 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'); }); }); ``` -------------------------------- ### Generate and Save PDF from Blade View in Laravel Source: https://spatie.be/docs/laravel-pdf/v1/introduction This snippet demonstrates how to create a PDF file from a Blade view in a Laravel application. It utilizes the Spatie Laravel PDF package to render a specified view with data and save it as a PDF. Dependencies include the Spatie Laravel PDF package and Browsershot. ```php use Spatie\LaravelPdf\Facades\Pdf; Pdf::view('pdfs.invoice', ['invoice' => $invoice]) ->format('a4') ->save('invoice.pdf'); ``` -------------------------------- ### HTML Invoice View with Tailwind CSS Source: https://spatie.be/docs/laravel-pdf/v1/advanced-usage/using-tailwind A Blade view demonstrating how to create a visually appealing PDF invoice using Tailwind CSS via CDN. This view includes placeholders for dynamic data like invoice number and customer name. ```html Invoice
Your Company Name
Invoice
Date: 01/05/2023
Invoice #: {{ $invoiceNumber }}

Bill To:

{{ $customerName }}
123 Main St.
Anytown, USA 12345
johndoe@example.com
Description Quantity Price Total
Product 1 1 $100.00 $100.00
Product 2 2 $50.00 $100.00
Product 3 3 $75.00 $225.00
Subtotal:
$425.00
Tax:
$25.50
Total:
$450.50
Payment is due within 30 days. Late payments are subject to fees.
Please make checks payable to Your Company Name and mail to:
123 Main St., Anytown, USA 12345
``` -------------------------------- ### Add Custom Macro to PdfBuilder in Laravel Source: https://spatie.be/docs/laravel-pdf/v1/advanced-usage/extending-with-macros This code snippet demonstrates how to add a custom macro named 'withCustomHeader' to the Spatie Laravel-pdf PdfBuilder class. It's typically placed in your application's service provider's boot method. This macro allows you to set custom HTML for the PDF header. ```php use Spatie\LaravelPdf\PdfBuilder; class AppServiceProvider extends ServiceProvider { public function boot() { PdfBuilder::macro('withCustomHeader', function (string $title) { $this->headerHtml = "

{$title}

"; return $this; }); } } ``` -------------------------------- ### Per-PDF Browsershot Customization in Laravel PDF Source: https://spatie.be/docs/laravel-pdf/v1/advanced-usage/customizing-browsershot This snippet demonstrates customizing a specific PDF's Browsershot instance using the withBrowsershot method on the Pdf facade. It requires the Spatie LaravelPdf and Browsershot packages. The closure receives a Browsershot instance for modifications like scaling, and the PDF is saved to a target path; limitations include it overriding only after defaults are applied. ```PHP use Spatie\LaravelPdf\Facades\Pdf; use Spatie\Browsershot\Browsershot; Pdf::view('test') ->withBrowsershot(function (Browsershot $browsershot) { $browsershot->scale(0.5); }) ->save($this->targetPath); ``` -------------------------------- ### Assert PDF Response in Laravel Controller Source: https://spatie.be/docs/laravel-pdf/v1/basic-usage/testing-pdfs The `assertRespondedWithPdf` method checks if a PDF was generated and returned as a response from a route. It can be used in tests to ensure that a download response is correctly formed and optionally inspect the PDF's content. This requires the spatie/laravel-pdf package and is often used in conjunction with a route definition. ```php use Spatie\LaravelPdf\Facades\Pdf; Route::get('download-invoice', function () { return pdf('pdf.invoice')->download('invoice-for-april-2022.pdf'); }); ``` ```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'); }); }); ``` -------------------------------- ### Assert PDF saved to path in Laravel Source: https://spatie.be/docs/laravel-pdf/v1/basic-usage/testing-pdfs Uses the assertSaved method to verify that a PDF file was saved to the specified filesystem path. Requires the Laravel PDF package and proper filesystem permissions. ```PHP Pdf::assertSaved(storage_path('invoices/invoice.pdf')); ``` -------------------------------- ### Override Browsershot Settings in PHP Source: https://spatie.be/docs/laravel-pdf/v1/advanced-usage/configuration Uses the Laravel PDF facade with withBrowsershot method to customize Browsershot settings for individual PDFs. Requires Spatie\LaravelPdf and Spatie\Browsershot imports. Inputs: view name, data array, closure modifying Browsershot. Outputs: customized PDF file. Runs after defaults, allowing full override. ```php use Spatie\LaravelPdf\Facades\Pdf; use Spatie\Browsershot\Browsershot; // This PDF will use the configuration defaults plus the scale override Pdf::view('invoice', ['invoice' => $invoice]) ->withBrowsershot(function (Browsershot $browsershot) { $browsershot->scale(0.8); }) ->save('invoice.pdf'); ``` -------------------------------- ### Use Custom PdfBuilder Macro in Laravel Source: https://spatie.be/docs/laravel-pdf/v1/advanced-usage/extending-with-macros This code snippet shows how to utilize a custom macro, 'withCustomHeader', that has been added to the PdfBuilder class. Once defined, you can chain this method like any other PdfBuilder method to customize your PDF output, such as adding a specific header. ```php use Spatie\LaravelPdf\Facades\Pdf; Pdf::view('invoice') ->withCustomHeader('Invoice #123') ->save('invoice.pdf'); ``` -------------------------------- ### Assert PDF Saved with Specific Properties in Laravel Source: https://spatie.be/docs/laravel-pdf/v1/basic-usage/testing-pdfs Use the `assertSaved` method to verify that a PDF was saved with specific attributes. It accepts a callable that receives a `PdfBuilder` instance. The assertion passes if the callable returns true. This method is useful for checking properties like the download name or HTML content. ```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'); }); ``` ```php use Spatie\LaravelPdf\Facades\Pdf; use Spatie\LaravelPdf\PdfBuilder; Pdf::assertSaved(function (PdfBuilder $pdf, string $path) { return $path === storage_path('invoices/invoice.pdf'); }); ``` -------------------------------- ### Set HTML Background Color for PDF Generation (CSS) Source: https://spatie.be/docs/laravel-pdf/v1/basic-usage/formatting-pdfs This CSS snippet enables the background color of the HTML page to be rendered in the generated PDF. It uses the `-webkit-print-color-adjust: exact;` property, which is essential for ensuring that background colors are not omitted during the printing or PDF generation process. This method is applied directly within the HTML or CSS file that is converted to a PDF. ```css ``` -------------------------------- ### Insert Page Breaks in Laravel Blade Templates Source: https://spatie.be/docs/laravel-pdf/v1/advanced-usage/creating-pdfs-with-multiple-pages The @pageBreak Blade directive is used to force a new page in the generated PDF, allowing content to be split across multiple pages. This requires the Laravel-PDF package which leverages Browsershot for rendering. The input is a Blade view with the directive, and output is a multi-page PDF file; limitations include browser rendering dependencies. ```blade
Page 1
@pageBreak
Page 2
``` ```php Pdf::view('view-with-multiple-pages')->save($path); ``` -------------------------------- ### Add Page Numbers in PDF Footers - Laravel Blade Source: https://spatie.be/docs/laravel-pdf/v1/advanced-usage/creating-pdfs-with-multiple-pages The @pageNumber and @totalPages Blade directives enable embedding dynamic page numbering in PDF footers. This feature is part of the Laravel-PDF package, requiring a separate footer view to be specified during rendering. Inputs are the main view and footer view, outputs are PDFs with numbered pages; it depends on Browsershot and may have layout limitations in complex designs. ```blade
This is page @pageNumber of @totalPages
``` ```php Pdf::view('view-with-multiple-pages')->footerView('footer-view')->save($path); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.