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

niklasravnsborg/laravel-pdf

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require niklasravnsborg/laravel-pdf
    

    For Laravel < 5.5, manually add the service provider and facade to config/app.php.

  2. Publish Config:

    php artisan vendor:publish --provider="niklasravnsborg\LaravelPdf\PdfServiceProvider"
    

    (Note: The package is archived; verify config compatibility with your Laravel version.)

  3. First Use Case: Create a Blade view (resources/views/pdf/invoice.blade.php) and generate a PDF in a controller:

    use PDF;
    public function generateInvoice() {
        $data = ['invoice' => Invoice::find(1)];
        return PDF::loadView('pdf.invoice', $data)->stream('invoice.pdf');
    }
    

Implementation Patterns

Core Workflows

  1. View-Based PDFs:

    • Use Blade templates (loadView) for dynamic content.
    • Pass data like a normal Laravel view:
      PDF::loadView('pdf.report', ['users' => User::all()])->stream();
      
  2. Direct HTML Strings:

    • Generate PDFs from raw HTML strings (e.g., API responses):
      $html = '<h1>Hello</h1><p>World</p>';
      PDF::loadHtml($html)->stream('dynamic.pdf');
      
  3. File Storage:

    • Save PDFs to disk instead of streaming:
      $pdf = PDF::loadView('pdf.manual', ['data' => $manual]);
      $pdf->save(storage_path('app/manual.pdf'));
      
  4. Queueing for Async Generation:

    • Dispatch a job to generate PDFs in the background:
      GeneratePdfJob::dispatch($userId, 'receipt');
      

    (Note: Requires custom job class with PDF::loadView() logic.)

Integration Tips

  • Laravel Mail: Attach PDFs to emails:

    Mail::send([], [], function($message) use ($pdf) {
        $message->subject('Your PDF');
        $message->attachData($pdf->output(), 'document.pdf');
    });
    
  • Laravel Storage: Use Storage::disk('s3')->put() to upload PDFs to cloud storage.

  • Dynamic Filenames: Use timestamps or model IDs:

    $filename = "invoice_{$invoice->id}_{$invoice->created_at->format('Y-m-d')}.pdf";
    PDF::loadView('pdf.invoice', ['invoice' => $invoice])->stream($filename);
    
  • Custom mPDF Config: Override defaults via config (e.g., paper size, margins):

    PDF::loadView('pdf.document')->setOption('default', 'P')->setOption('format', 'A4');
    

Gotchas and Tips

Pitfalls

  1. Deprecated Package:

    • The package is archived (last update: 2023-08-22). Use misterspelik/laravel-pdf for active maintenance.
    • Test thoroughly; some Laravel versions (e.g., 9.x) may require polyfills or config tweaks.
  2. mPDF Version Conflicts:

    • The package bundles an older mpdf/mpdf version. Conflicts may arise with other packages using mPDF.
    • Fix: Use composer require mpdf/mpdf:^8.0 and configure the package to use the global mPDF instance.
  3. Memory Limits:

    • Complex PDFs (e.g., large tables) may hit PHP’s memory_limit.
    • Tip: Increase memory_limit in php.ini or chunk data processing.
  4. Font Issues:

    • Custom fonts may not render. Ensure fonts are installed on the server or use mPDF’s built-in fonts.
    • Workaround: Add fonts via mPDF’s setFontDir() or use @font-face in CSS (limited support).
  5. Caching:

    • Blade views cached by Laravel may cause stale PDFs. Use ->stream() with unique filenames or disable caching for PDF routes.

Debugging

  • Check mPDF Logs: Enable mPDF debugging in config/laravel-pdf.php:

    'debug' => true,
    

    Logs appear in Laravel’s storage/logs/laravel.log.

  • Inspect HTML: Save the generated HTML to a file before PDF conversion to debug rendering:

    file_put_contents(storage_path('debug.html'), $pdf->getHtml());
    
  • Common Errors:

    • "Class not found": Run composer dump-autoload.
    • "Call to undefined method": Verify method signatures (e.g., loadView vs. loadHtml).
    • Blank PDFs: Check for invalid HTML or missing CSS (use inline styles if needed).

Extension Points

  1. Custom mPDF Instance: Override the default mPDF instance in a service provider:

    $this->app->bind('mpdf', function() {
        $mpdf = new \Mpdf\Mpdf(['mode' => 'utf-8', 'format' => 'A4']);
        return $mpdf;
    });
    
  2. Middleware for PDFs: Add headers or auth checks:

    Route::get('/pdf', function() {
        return PDF::loadView('pdf.document')->stream();
    })->middleware('auth');
    
  3. PDF Metadata: Set document properties (title, author) via mPDF:

    PDF::loadView('pdf.document')
        ->setOption('title', 'My Document')
        ->setOption('author', 'Laravel App');
    
  4. Barcode/QR Codes: Use mPDF’s extensions (e.g., mpdf/barcodes) for dynamic codes:

    $pdf->setOption('barcode_width', '0.2');
    $pdf->setOption('barcode_height', '25');
    
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware