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

Laravel wrapper for Dompdf to generate PDFs from HTML views. Provides a PDF facade/service, easy rendering, streaming or downloading responses, and simple configuration—ideal for invoices, reports, and other printable documents in Laravel apps.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require barryvdh/laravel-dompdf
    

    Laravel will auto-discover the package. No manual service provider registration is required.

  2. Publish Config (Optional):

    php artisan vendor:publish --provider="Barryvdh\DomPDF\ServiceProvider" --tag=config
    

    This publishes config/dompdf.php for customization.

  3. First Use Case: Generate a PDF from a Blade view:

    use Barryvdh\DomPDF\Facade\Pdf;
    
    $pdf = Pdf::loadView('pdf.invoice', ['data' => $invoiceData]);
    return $pdf->download('invoice.pdf');
    

Key Starting Points

  • Facade: Barryvdh\DomPDF\Facade\Pdf (preferred) or Barryvdh\DomPDF\Facade\PDF (legacy).
  • Direct Usage: Resolve the service via app('dompdf.wrapper').
  • Documentation: Official Docs (focus on the "Usage" section).

Implementation Patterns

Core Workflows

  1. Loading Content:

    • Blade Views:
      $pdf = Pdf::loadView('view.name', $data);
      
    • HTML Strings:
      $pdf = Pdf::loadHtml('<h1>Hello</h1>');
      
    • URLs:
      $pdf = Pdf::load('https://example.com');
      
  2. Output Methods:

    • Download:
      return Pdf::loadView('view')->download('filename.pdf');
      
    • Stream:
      return Pdf::loadView('view')->stream('filename.pdf');
      
    • Save to File:
      $pdf->save(storage_path('app/filename.pdf'));
      
    • Return as String:
      $pdfString = Pdf::loadView('view')->output();
      
  3. Dynamic Options:

    $pdf = Pdf::loadView('view')
        ->setOption('defaultFont', 'Courier')
        ->setOption('isRemoteEnabled', true)
        ->setOption('isPhpEnabled', true);
    
  4. Chaining with DomPDF Methods: Leverage "magic methods" to call DomPDF directly:

    $pdf = Pdf::loadView('view')
        ->setPaper('A4', 'landscape')
        ->bookmark('Section 1');
    

Integration Tips

  • Queue PDF Generation: Use Laravel Queues to offload heavy PDF generation:

    Pdf::loadView('view')->save(storage_path('app/queued.pdf'));
    // Later, send the file via email or download.
    
  • Custom Fonts: Add fonts via the addFont() method or configure in dompdf.php:

    Pdf::loadView('view')->addFont('path/to/font.ttf', 'FontName');
    
  • Headers/Footers: Use DomPDF’s setFooter() and setHeader() methods or inject via HTML/CSS:

    $pdf = Pdf::loadView('view')
        ->setFooter('Page {PAGE_NUM} of {PAGE_COUNT}');
    
  • API Responses: Return PDFs in API responses with proper headers:

    return response($pdf->output(), 200, [
        'Content-Type' => 'application/pdf',
        'Content-Disposition' => 'inline; filename="document.pdf"',
    ]);
    
  • Testing: Use Pdf::loadHtml() with static HTML for unit tests:

    $pdf = Pdf::loadHtml('<h1>Test</h1>');
    $this->assertStringContainsString('Test', $pdf->output());
    

Gotchas and Tips

Pitfalls

  1. Deprecated Methods:

    • Avoid setOptions() (use setOption() for granular changes).
    • orientation config is obsolete; use default_paper_orientation in dompdf.php.
  2. Security:

    • Remote Content: isRemoteEnabled is false by default (v3.x). Enable only if needed:
      Pdf::load('https://trusted-site.com')->setOption('isRemoteEnabled', true);
      
    • Allowed Protocols: Ensure data:// is included if using data URIs (v3.1+):
      'allowed_protocols' => ['http', 'https', 'ftp', 'data'],
      
  3. Font Issues:

    • Missing fonts may cause silent failures. Verify paths in dompdf.php:
      'font_dir' => storage_path('fonts'),
      'font_cache' => storage_path('fonts/cache'),
      
  4. Memory Limits:

    • Complex PDFs may hit PHP memory limits. Adjust in dompdf.php:
      'memory_limit' => '1024M',
      
  5. Legacy Laravel:

    • Drop support for Laravel <9 and PHP <8.1 (v3.x). Use v2.x for older stacks.

Debugging Tips

  • Inspect Generated HTML: Use Pdf::loadHtml($html)->debug() to preview rendering issues.
  • Check Logs: Enable DomPDF logging in dompdf.php:
    'debug_pdf' => true,
    
  • Validate Config: Publish and review config/dompdf.php for overrides:
    php artisan vendor:publish --tag=dompdf-config
    

Extension Points

  1. Custom Wrapper: Extend Barryvdh\DomPDF\PDF for reusable logic:

    class CustomPDF extends Pdf {
        public function addWatermark($text) {
            $this->getDomPDF()->setWatermark($text);
        }
    }
    
  2. Event Listeners: Hook into DomPDF events (e.g., dompdf.create):

    Pdf::loadView('view')->onCreate(function ($dompdf) {
        $dompdf->setPaper('A5');
    });
    
  3. Middleware: Restrict PDF generation to authenticated users:

    Pdf::middleware('auth')->loadView('view');
    
  4. Service Provider: Bind custom configurations:

    $this->app->extend('dompdf.wrapper', function ($wrapper) {
        $wrapper->setOption('defaultFont', 'Helvetica');
        return $wrapper;
    });
    

Performance

  • Cache Fonts: DomPDF caches fonts in storage_path('fonts/cache'). Clear manually if fonts change:
    php artisan dompdf:clear-font-cache
    
  • Streaming: Use stream() for large PDFs to avoid memory spikes.
  • Lazy Loading: Load views/HTML dynamically to reduce initial load time.

Common Quirks

  • CSS Specificity: DomPDF may ignore complex CSS. Simplify styles or use inline styles.
  • Tables: Use table-layout: fixed for consistent table rendering.
  • Images: Ensure images are accessible (local paths or absolute URLs).
  • Unicode: Test with non-Latin characters; some fonts may lack glyphs.
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport