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

Chrome Pdf Bundle Laravel Package

dreadnip/chrome-pdf-bundle

Symfony bundle that uses chrome-php/chrome to render HTML to PDF via Chrome/Chromium. Configure the Chrome binary via env, then generate PDFs from HTML with the PdfGenerator service or customize via the BrowserFactory for advanced options.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation: Add the bundle via Composer in your Laravel project (using Symfony bridge if needed):

    composer require dreadnip/chrome-pdf-bundle
    

    Register the bundle in config/bundles.php:

    return [
        // ...
        Dreadnip\ChromePdfBundle\ChromePdfBundle::class => ['all' => true],
    ];
    
  2. Configure Chrome Path: Set the Chrome/Chromium binary path in .env:

    CHROME_BINARY="/usr/bin/chromium-browser"  # Linux
    CHROME_BINARY="C:\Program Files\Google\Chrome\Application\chrome.exe"  # Windows
    
  3. First Use Case: Generate a PDF from a Twig template in a controller:

    use Dreadnip\ChromePdfBundle\Service\PdfGenerator;
    use Symfony\Component\HttpFoundation\BinaryFileResponse;
    
    public function generatePdf(PdfGenerator $pdfGenerator)
    {
        $html = $this->render('pdf_template.twig');
        $path = $pdfGenerator->generate($html, 'storage/app/public/report.pdf');
        return new BinaryFileResponse($path);
    }
    

Where to Look First

  • Documentation: README.md for basic setup.
  • Services: Focus on PdfGenerator for simple use cases and BrowserFactory for advanced configurations.
  • Templates: Extend @ChromePdf/base.html.twig for consistent PDF layouts.

Implementation Patterns

Usage Patterns

  1. Basic PDF Generation: Use PdfGenerator for straightforward HTML-to-PDF conversion:

    $pdfGenerator->generate($html, 'path/to/file.pdf');
    
  2. Dynamic Templates: Combine with Laravel’s Blade or Twig to render dynamic content:

    $html = view('invoices.pdf', ['invoice' => $invoice])->render();
    $pdfGenerator->generate($html, 'storage/invoices/invoice_'.$invoice->id.'.pdf');
    
  3. Custom Print Options: Pass Chrome-specific print options for fine-grained control:

    $printOptions = [
        'printBackground' => true,
        'headerTemplate' => '<div>Custom Header</div>',
        'footerTemplate' => '<div>Page <span class="pageNumber"></span></div>',
    ];
    $pdfGenerator->generate($html, 'file.pdf', $printOptions);
    
  4. Browser Configuration: Adjust Chrome’s behavior (e.g., headless mode, timeout):

    $browserOptions = [
        'headless' => false, // Debugging
        'args' => ['--no-sandbox', '--disable-setuid-sandbox'],
        'timeout' => 60000,
    ];
    $pdfGenerator->generate($html, 'file.pdf', [], $browserOptions);
    
  5. Batch Processing: Queue PDF generation jobs (e.g., using Laravel Queues) for large datasets:

    PdfJob::dispatch($userId, $template)->onQueue('pdfs');
    
    // In PdfJob.php
    public function handle()
    {
        $html = view('reports.dashboard', ['user' => $this->userId])->render();
        $pdfGenerator->generate($html, "storage/reports/user_{$this->userId}.pdf");
    }
    

Workflows

  1. Invoice Generation:

    • Render Blade template with invoice data.
    • Generate PDF and attach to email:
      $pdfPath = $pdfGenerator->generate($html, 'temp/invoice.pdf');
      Mail::send([], [], function ($message) use ($pdfPath) {
          $message->attach($pdfPath);
      });
      
  2. Report Scheduling:

    • Use Laravel Tasks to generate PDFs nightly:
      $schedule->command('reports:generate')->daily();
      
      php artisan reports:generate
      
  3. Dynamic Dashboards:

    • Serve interactive PDFs with embedded JavaScript:
      $html = view('dashboards.pdf', ['data' => $dashboardData])->render();
      $pdfGenerator->generate($html, 'temp/dashboard.pdf', [
          'javascriptEnabled' => true,
      ]);
      

Integration Tips

  1. Laravel-Specific:

    • Use Laravel’s Storage facade to manage PDF paths:
      use Illuminate\Support\Facades\Storage;
      $path = Storage::path('pdfs/report.pdf');
      
    • Integrate with Laravel’s Response helpers for seamless downloads:
      return response()->download($path, 'report.pdf');
      
  2. Symfony Bridge:

    • If using spatie/laravel-symfony-bundle, ensure the bundle is registered before Laravel’s service providers.
  3. Testing:

    • Mock PdfGenerator in unit tests:
      $mock = Mockery::mock(PdfGenerator::class);
      $mock->shouldReceive('generate')->andReturn('fake/path.pdf');
      $this->app->instance(PdfGenerator::class, $mock);
      
  4. CI/CD:

    • Install Chrome/Chromium in CI environments (e.g., GitHub Actions):
      - name: Install Chrome
        run: |
          sudo apt-get update
          sudo apt-get install -y chromium-browser
      

Gotchas and Tips

Pitfalls

  1. Chrome Binary Path:

    • Issue: PDF generation fails silently if the Chrome path is incorrect.
    • Fix: Validate the path in .env and log errors:
      if (!file_exists($this->config['chrome_path'])) {
          Log::error('Chrome binary not found at: '.$this->config['chrome_path']);
      }
      
  2. Headless Mode:

    • Issue: Debugging is difficult in headless mode (headless: true).
    • Fix: Temporarily set headless: false for development:
      $browserOptions = ['headless' => env('APP_DEBUG') ? false : true];
      
  3. Timeouts:

    • Issue: Complex PDFs may exceed default timeouts (e.g., 30s).
    • Fix: Increase timeout for large documents:
      $pdfGenerator->generate($html, 'file.pdf', [], [], 120000); // 120s
      
  4. Resource Limits:

    • Issue: Chrome consumes significant memory/CPU, causing timeouts or crashes.
    • Fix: Limit concurrent jobs or use a queue:
      $pdfGenerator->generate($html, 'file.pdf', [], ['args' => ['--single-process']]);
      
  5. CSS/JS Dependencies:

    • Issue: PDFs may render incorrectly if external resources (e.g., fonts, scripts) are blocked.
    • Fix: Use localFileSystem or userDataDir in browser options:
      $browserOptions = [
          'userDataDir' => sys_get_temp_dir().'/chrome-pdf-user-data',
      ];
      

Debugging

  1. Logs:

    • Enable Chrome’s logging via args:
      $browserOptions = [
          'args' => ['--headless=new', '--disable-gpu', '--log-level=DEBUG'],
      ];
      
    • Check Laravel logs for Chrome errors:
      tail -f storage/logs/laravel.log | grep -i chrome
      
  2. Network Issues:

    • If PDFs fail to load external resources (e.g., images), use a local proxy or disable network access:
      $browserOptions = [
          'args' => ['--no-zygote', '--disable-dev-shm-usage', '--disable-gpu'],
      ];
      
  3. Memory Dumps:

    • For crashes, generate a memory dump:
      $browserOptions = [
          'args' => ['--js-flags="--expose-gc"'],
      ];
      

Configuration Quirks

  1. Environment Variables:

    • Override Chrome path per environment:
      CHROME_BINARY_LIVE="/usr/bin/chromium-live"
      CHROME_BINARY_STAGING="/usr/bin/chromium-staging"
      
    • Use Laravel’s env() helper:
      $chromePath = env('CHROME_BINARY_'.config('app.env'));
      
  2. Default Options:

    • Set defaults in config/packages/chrome_pdf.yaml:
      chrome_pdf:
          default_options:
              printBackground: true
              timeout: 60000
      
  3. Symfony vs. Laravel:

    • If using Symfony components directly, ensure autowiring is configured in config/autoload.php:
      $container->setParameter('chrome_pdf.chrome_path', env('CHROME_BIN
      
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.
andydefer/laravel-actions
aimeos/prisma
besmartand-pro/php-quality-config
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor