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

Php Weasyprint Laravel Package

pontedilana/php-weasyprint

Laravel-friendly PHP wrapper for WeasyPrint to render HTML/CSS into high-quality PDFs (and images) via a simple API. Ideal for invoices, reports, and templated documents, with options for assets, headers/footers, and configuration.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require pontedilana/php-weasyprint
    

    Ensure weasyprint is installed system-wide (check official docs for OS-specific instructions).

  2. Basic Usage Generate a PDF from HTML:

    use Pontedilana\WeasyPrint\WeasyPrint;
    
    $html = '<h1>Hello, PDF!</h1><p>Generated with WeasyPrint.</p>';
    $pdf = WeasyPrint::fromHtml($html)->toPdf();
    file_put_contents('output.pdf', $pdf);
    
  3. First Use Case Convert a Blade view to PDF in a Laravel controller:

    use Pontedilana\WeasyPrint\WeasyPrint;
    use Illuminate\Support\Facades\View;
    
    $html = View::make('pdf.template', ['data' => $model])->render();
    $pdf = WeasyPrint::fromHtml($html)->toPdf();
    return response($pdf, 200, [
        'Content-Type' => 'application/pdf',
        'Content-Disposition' => 'inline; filename="document.pdf"'
    ]);
    

Implementation Patterns

Common Workflows

  1. From URLs

    $pdf = WeasyPrint::fromUrl('https://example.com')->toPdf();
    
  2. With CSS Styling

    $pdf = WeasyPrint::fromHtml($html)
        ->setCss('path/to/styles.css')
        ->toPdf();
    
  3. Streaming Responses

    return WeasyPrint::fromHtml($html)
        ->streamPdf('document.pdf');
    
  4. Dynamic Content Loop through models and generate PDFs in batches:

    foreach ($models as $model) {
        $html = View::make('pdf.template', compact('model'))->render();
        $pdf = WeasyPrint::fromHtml($html)->toPdf();
        Storage::put("pdfs/{$model->id}.pdf", $pdf);
    }
    
  5. Integration with Queues Dispatch a job for async PDF generation:

    GeneratePdfJob::dispatch($html, 'output.pdf');
    

Laravel-Specific Tips

  • Service Provider Binding Bind the package for dependency injection:

    $this->app->bind(WeasyPrint::class, function ($app) {
        return new WeasyPrint(config('weasyprint.defaults'));
    });
    
  • Config Overrides Publish the config file:

    php artisan vendor:publish --provider="Pontedilana\WeasyPrint\WeasyPrintServiceProvider"
    

    Customize config/weasyprint.php for default options (e.g., timeout, CSS paths).

  • Middleware for Authenticated PDFs Protect PDF endpoints:

    Route::get('/pdf/{id}', function ($id) {
        return WeasyPrint::fromHtml($html)->streamPdf("document_{$id}.pdf");
    })->middleware('auth');
    

Gotchas and Tips

Pitfalls

  1. WeasyPrint System Dependency

    • Error: Command 'weasyprint' not found.
    • Fix: Install WeasyPrint via package manager (e.g., brew install weasyprint on macOS or apt-get install weasyprint on Ubuntu).
    • Debug: Verify with weasyprint --version in terminal.
  2. Memory Limits

    • Error: Allowed memory size exhausted for large HTML.
    • Fix: Increase PHP memory (ini_set('memory_limit', '1G')) or optimize HTML/CSS.
  3. CSS Inline vs. External

    • Gotcha: External CSS may fail if paths are relative.
    • Fix: Use absolute paths or inline critical CSS:
      $pdf = WeasyPrint::fromHtml($html)
          ->setCss('https://example.com/styles.css')
          ->toPdf();
      
  4. Timeouts

    • Error: PDF generation hangs on URLs.
    • Fix: Set a timeout in config:
      'timeout' => 30, // seconds
      

Debugging

  • Log WeasyPrint Output Enable verbose logging in config:

    'verbose' => true,
    

    Check Laravel logs for WeasyPrint CLI output.

  • Test with Minimal HTML Isolate issues by testing with a simple <div> before complex templates.

Extension Points

  1. Custom Headers/Footers Use CSS @page rules:

    @page {
        size: A4;
        margin: 2cm;
    }
    header {
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        height: 1cm;
    }
    
  2. Post-Processing Modify PDFs after generation with libraries like setasign/fpdf:

    $pdfContent = WeasyPrint::fromHtml($html)->toPdf();
    $pdf = \FPDF::parse($pdfContent);
    // Add watermark, etc.
    
  3. Caching Cache generated PDFs for static content:

    $pdf = Cache::remember("pdf_{$key}", now()->addHours(1), function () {
        return WeasyPrint::fromHtml($html)->toPdf();
    });
    

Pro Tips

  • Use ->toSnapshot() for Images Generate screenshots of URLs:

    $image = WeasyPrint::fromUrl('https://example.com')->toSnapshot();
    file_put_contents('screenshot.png', $image);
    
  • Laravel Mix Integration Compile CSS for WeasyPrint in your build process:

    // webpack.mix.js
    mix.postCss('resources/css/pdf.css', 'public/css', [
        require('postcss-import'),
        require('tailwindcss')
    ]);
    
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