Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Pdf Laravel Package

spatie/laravel-pdf

Generate PDFs from Laravel Blade views with a simple fluent API. Choose drivers like Browsershot/Chromium, Gotenberg, Cloudflare Browser Run, WeasyPrint, DOMPDF, or chrome-php. Use modern CSS, set page formats, and stream or save PDFs.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require spatie/laravel-pdf
    php artisan vendor:publish --provider="Spatie\Pdf\PdfServiceProvider"
    

    Publish the config file to adjust default settings (e.g., driver, paths).

  2. First Use Case: Generate a PDF from a Blade view in a controller:

    use Spatie\Pdf\Facades\Pdf;
    
    public function generatePdf()
    {
        return Pdf::view('pdfs.invoice', ['data' => $data])
            ->format('a4')
            ->name('document.pdf');
    }
    
  3. Key Files to Review:

    • config/pdf.php: Driver configuration (e.g., browsershot, dompdf).
    • resources/views/pdfs/: Store Blade templates for PDFs.
    • app/Providers/AppServiceProvider.php: Register macros or custom logic if needed.

Implementation Patterns

Core Workflows

  1. Driver Selection:

    • Use Pdf::driver('dompdf') for lightweight, dependency-free PDFs.
    • Use Pdf::driver('browsershot') for modern CSS (e.g., Flexbox/Grid) support.
    • Use Pdf::driver('gotenberg') for Docker-based, scalable PDF generation.
    Pdf::driver('dompdf')->view('pdfs.report')->save('report.pdf');
    
  2. Dynamic PDF Generation:

    • Pass data to Blade views:
      Pdf::view('pdfs.invoice', ['user' => $user, 'items' => $items])
          ->format('a4')
          ->save(storage_path("app/{$user->id}_invoice.pdf"));
      
  3. Queued PDFs:

    • Offload PDF generation to a queue:
      Pdf::view('pdfs.heavy-report', ['data' => $data])
          ->saveQueued('reports/heavy-report.pdf');
      
  4. Email Attachments:

    • Attach PDFs to emails using toMailAttachment():
      $pdf = Pdf::view('pdfs.quote', ['quote' => $quote])
          ->name('quote.pdf')
          ->toMailAttachment();
      
      Mail::send([...], function ($message) use ($pdf) {
          $message->attach($pdf);
      });
      
  5. Macros for Reusability:

    • Extend PdfBuilder with custom methods in AppServiceProvider:
      Pdf::macro('withLogo', function () {
          return $this->withOptions(['header-html' => view('pdfs.header')]);
      });
      
      // Usage:
      Pdf::view('pdfs.document')->withLogo()->save('document.pdf');
      

Integration Tips

  • CSS/Styling:

    • Use Browsershot/WeasyPrint for advanced CSS (e.g., @page rules for headers/footers).
    • Avoid complex JavaScript in Blade templates (some drivers may not execute it).
  • Testing:

    • Use Pdf::fake() to mock PDF generation in tests:
      Pdf::fake();
      $response = $this->get('/download-pdf');
      Pdf::assertRespondedWithPdf();
      
  • Storage:

    • Save PDFs to disk, S3, or database using save(), saveQueued(), or generatePdfContent():
      $pdfContent = Pdf::view('pdfs.document')->generatePdfContent();
      Storage::disk('s3')->put('documents/report.pdf', $pdfContent);
      

Gotchas and Tips

Pitfalls

  1. Driver Compatibility:

    • DOMPDF: Limited CSS support (e.g., no Flexbox/Grid). Use for simple layouts.
    • Browsershot/WeasyPrint: Require external dependencies (Chromium/Python). Ensure puppeteer/poppler-utils are installed.
    • Gotenberg: Needs a running Docker container. Configure GOTENBERG_URL in .env.
  2. Memory Limits:

    • Large PDFs (e.g., multi-page reports) may hit memory limits. Use saveQueued() or optimize Blade templates.
  3. Local File Access:

    • Browsershot blocks local file access by default. Disable sandbox for testing:
      Pdf::driver('browsershot')->withBrowsershot(function ($browsershot) {
          $browsershot->setOption('disable-web-security', true);
      });
      
  4. Queue Defaults:

    • Queued jobs may not inherit all PdfBuilder options. Explicitly set defaults in PdfServiceProvider:
      Pdf::macro('setDefaults', function () {
          Pdf::setOption('format', 'a4');
          Pdf::setOption('margin-top', '20mm');
      });
      
  5. Testing Quirks:

    • Pdf::fake() only works with Pdf::view() or Pdf::loadView(). Avoid Pdf::load() in tests.
    • Assertions like contains() are case-sensitive and require the PDF to be saved first.

Debugging

  • Logs:
    • Enable debug mode in config/pdf.php to log driver errors:
      'debug' => env('PDF_DEBUG', false),
      
  • Driver-Specific Issues:
    • Browsershot: Check Chromium binary path in config/browsershot.php.
    • Gotenberg: Verify Docker container is running (docker ps).
    • DOMPDF: Ensure no syntax errors in Blade templates (DOMPDF is strict).

Extension Points

  1. Custom Drivers:

    • Implement Spatie\Pdf\Contracts\Driver to add support for new backends (e.g., headless Chrome via chrome-php/chrome).
  2. PDF Metadata:

    • Set metadata (title, author, etc.) via setMetadata():
      Pdf::view('pdfs.document')
          ->setMetadata([
              'title' => 'My Document',
              'author' => 'Laravel App',
          ])
          ->save('document.pdf');
      
  3. Headers/Footers:

    • Use header-html/footer-html options with Browsershot/WeasyPrint:
      Pdf::view('pdfs.report')
          ->withOptions([
              'header-html' => view('pdfs.header', ['page' => '<page>']),
              'footer-html' => view('pdfs.footer'),
          ])
          ->save('report.pdf');
      
  4. Raw Content:

    • Access raw PDF content without saving:
      $pdfContent = Pdf::view('pdfs.document')->generatePdfContent();
      // Use $pdfContent (e.g., send via API or store in DB)
      

Configuration Quirks

  • Default Driver:

    • Set in config/pdf.php under default_driver. Override per call with Pdf::driver('name').
  • Browsershot Options:

    • Pass custom options via withBrowsershot():
      Pdf::driver('browsershot')
          ->withBrowsershot(function ($browsershot) {
              $browsershot->setOption('timeout', 30000);
          })
          ->view('pdfs.document')
          ->save('document.pdf');
      
  • WeasyPrint:

    • Requires Python and weasyprint installed. Configure in config/pdf.php:
      'weasyprint' => [
          'binary' => '/usr/local/bin/weasyprint',
      ],
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
codraw/framework-extra-bundle
codraw/messenger
codraw/security
codraw/mailer
codraw/contracts
codraw/profiling
codraw/dependency-injection
codraw/tester
codraw/core
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony