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 Dompdf Laravel Package

barryvdh/laravel-dompdf

Generate PDFs in Laravel using Dompdf. Render Blade views or HTML to PDF, set paper size/orientation, stream or download responses, and configure fonts/options. Popular, straightforward integration for invoices, reports, and documents.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require barryvdh/laravel-dompdf
    

    Publish the config (optional but recommended for customization):

    php artisan vendor:publish --provider="Barryvdh\DomPDF\ServiceProvider" --tag=config
    
  2. First Use Case: Generate a PDF from a Blade view:

    use Barryvdh\DomPDF\Facade\Pdf;
    
    $pdf = Pdf::loadView('pdf.invoice');
    return $pdf->download('invoice.pdf');
    
  3. Key Files:

    • config/dompdf.php: Central configuration (e.g., paper size, security settings).
    • resources/views/pdf/*.blade.php: Blade templates for PDF content.

Implementation Patterns

Core Workflows

  1. Loading Content:

    // From a Blade view
    Pdf::loadView('view.name', $data)->save('file.pdf');
    
    // From a string
    Pdf::loadHTML('<h1>Hello</h1>')->stream();
    
    // From a URL (if `enable_remote` is true)
    Pdf::load('https://example.com')->download('remote.pdf');
    
  2. Dynamic Options: Override defaults per request:

    Pdf::loadView('view.name')
        ->setOption('isHtml5ParserEnabled', true)
        ->setOption('defaultFont', 'DejaVu Sans')
        ->stream();
    
  3. Output Methods:

    • Download: Force browser download.
      return Pdf::loadView('view.name')->download('filename.pdf');
      
    • Stream: Display in browser.
      return Pdf::loadView('view.name')->stream();
      
    • Save: Store locally.
      Pdf::loadView('view.name')->save(storage_path('app/file.pdf'));
      
  4. Integration with Controllers:

    public function generateReport(Request $request) {
        $pdf = Pdf::loadView('reports.daily', [
            'data' => $request->user()->reports
        ]);
        return $pdf->setPaper('a4', 'landscape')->stream('report.pdf');
    }
    
  5. Queueing for Background Jobs: Use Laravel queues to offload PDF generation:

    // Job class
    public function handle() {
        $pdf = Pdf::loadView('pdf.bulk-report', ['data' => $this->data]);
        Storage::put('reports/' . $this->filename . '.pdf', $pdf->output());
    }
    
  6. Custom Fonts: Add fonts via config:

    'font_dir' => public_path('fonts'),
    'font_data' => [
        'DejaVu Sans' => Pdf::font('DejaVuSans.ttf', 'DejaVu Sans'),
    ],
    

Gotchas and Tips

Common Pitfalls

  1. Security:

    • enable_remote is false by default (v3.x). Explicitly allow remote URLs:
      'enable_remote' => true,
      'allowedRemoteHosts' => ['*.example.com'],
      
    • Data URIs: Ensure data:// is in allowed_protocols if using inline assets:
      'allowed_protocols' => ['http', 'https', 'ftp', 'ftps', 'data'],
      
  2. Deprecated Methods:

    • Avoid setOptions() (use setOption() for granular control).
    • Facade alias changed: Use Pdf (not PDF) for consistency.
  3. Font Issues:

    • Verify font paths in font_dir and font_data config.
    • Use absolute paths (e.g., public_path('fonts/DejaVuSans.ttf')).
  4. CSS Quirks:

    • Complex layouts may need !important or inline styles.
    • Test with isRemoteEnabled and isPhpEnabled for debugging:
      Pdf::loadHTML($html)->setOption('isRemoteEnabled', true);
      
  5. Performance:

    • Cache compiled PDFs for static content:
      if (!Storage::exists("cache/{$filename}.pdf")) {
          $pdf->save(storage_path("cache/{$filename}.pdf"));
      }
      return response()->file(storage_path("cache/{$filename}.pdf"));
      

Debugging Tips

  1. Inspect HTML: Use ->debug() to dump the rendered HTML before PDF conversion:

    Pdf::loadView('view.name')->debug();
    
  2. Log Errors: Enable DomPDF’s error handling:

    Pdf::loadHTML($html)->setOption('isErrorHandlerEnabled', true);
    
  3. Check Config: Validate dompdf.php for typos (e.g., allowedRemoteHosts vs. allowed_remote_hosts).

Extension Points

  1. Custom Paper Sizes: Extend via config:

    'paper' => [
        'custom' => ['width' => 210, 'height' => 297], // A4 in mm
    ],
    
  2. Event Listeners: Hook into DomPDF’s lifecycle (e.g., post-generation):

    Pdf::loadView('view.name')->after(function ($pdf) {
        Log::info('PDF generated with ID: ' . $pdf->getId());
    });
    
  3. Headless Chrome Integration: For dynamic content, use Laravel’s Puppeteer or Playwright to generate HTML first, then pass to DomPDF.

  4. Testing: Use Mockery to stub PDF generation in unit tests:

    $mock = Mockery::mock('overload:Barryvdh\DomPDF\Facade\Pdf');
    $mock->shouldReceive('loadView')->andReturnSelf();
    $mock->shouldReceive('stream')->andReturn('mocked-pdf');
    
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.
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope
anil/file-picker
broqit/fields-ai