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

Phpwkhtmltopdf Laravel Package

mikehaertl/phpwkhtmltopdf

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require mikehaertl/phpwkhtmltopdf
    

    Ensure wkhtmltopdf is installed on your system (download from wkhtmltopdf.org).

  2. Basic Usage:

    use MikeHaertl\Phpwkhtmltopdf\Pdf;
    
    $pdf = new Pdf();
    $pdf->addPage('Hello, World!');
    $pdf->saveAs(storage_path('test.pdf'));
    
  3. First Use Case: Generate a PDF from a Blade template:

    $pdf = new Pdf();
    $pdf->addPage( view('pdf.template', ['data' => $data])->render() );
    $pdf->saveAs(storage_path('invoice.pdf'));
    

Implementation Patterns

Common Workflows

  1. Dynamic PDF Generation:

    $pdf = new Pdf();
    $pdf->addPageHTML('<h1>Dynamic Content</h1><p>' . $user->name . '</p>');
    $pdf->saveAs(storage_path('user_' . $user->id . '.pdf'));
    
  2. Reusable PDF Service:

    class PdfService {
        public function generateInvoice($user, $invoiceData) {
            $pdf = new Pdf();
            $pdf->addPage(view('invoice.pdf', compact('user', 'invoiceData'))->render());
            return $pdf->output();
        }
    }
    
  3. Streaming PDFs to Browser:

    $pdf = new Pdf();
    $pdf->addPageHTML('<h1>Download Me</h1>');
    $pdf->stream('filename.pdf');
    
  4. Customizing wkhtmltopdf Options:

    $pdf = new Pdf();
    $pdf->setOption('orientation', 'Landscape');
    $pdf->setOption('margin-top', '20mm');
    $pdf->addPageHTML('<h1>Custom Layout</h1>');
    $pdf->saveAs(storage_path('custom.pdf'));
    
  5. Queueing PDF Jobs:

    // In your job class
    public function handle() {
        $pdf = new Pdf();
        $pdf->addPageHTML('<h1>Queued PDF</h1>');
        $pdf->saveAs(storage_path('queued.pdf'));
    }
    

Gotchas and Tips

Pitfalls

  1. Binary Path Issues:

    • Ensure wkhtmltopdf is in your system PATH or specify its path explicitly:
      $pdf = new Pdf('/usr/local/bin/wkhtmltopdf');
      
    • Debug with which wkhtmltopdf (Linux/Mac) or check where wkhtmltopdf (Windows).
  2. Memory Limits:

    • Large PDFs may hit PHP memory limits. Increase memory_limit in php.ini or use chunked processing.
  3. Font Handling:

    • wkhtmltopdf requires fonts to be installed on the server. Use absolute paths for custom fonts:
      $pdf->addFont('/path/to/font.ttf', 'CustomFont');
      $pdf->setOption('font-name', 'CustomFont');
      
  4. CSS Quirks:

    • wkhtmltopdf has limited CSS3 support. Test styles in a browser first, then in the PDF.
  5. Headless Environments:

    • Ensure wkhtmltopdf is installed in CI/CD pipelines (e.g., Docker containers). Example Dockerfile snippet:
      RUN apt-get update && apt-get install -y wkhtmltopdf
      

Debugging

  • Verbose Output: Enable debug mode to see underlying wkhtmltopdf commands:
    $pdf->setOption('quiet', false);
    
  • Error Handling: Wrap PDF generation in try-catch:
    try {
        $pdf->saveAs('file.pdf');
    } catch (\MikeHaertl\Phpwkhtmltopdf\Exception\PdfException $e) {
        Log::error($e->getMessage());
    }
    

Tips

  1. Caching: Cache generated PDFs to avoid reprocessing:

    if (!file_exists(storage_path('cached.pdf'))) {
        $pdf->saveAs(storage_path('cached.pdf'));
    }
    
  2. Options Reference: Consult wkhtmltopdf options for advanced configurations like headers/footers, page numbers, or custom margins.

  3. Laravel Integration: Use response()->make() for seamless HTTP responses:

    return response()->make($pdf->output(), 200, [
        'Content-Type' => 'application/pdf',
        'Content-Disposition' => 'inline; filename="document.pdf"',
    ]);
    
  4. Testing: Mock the Pdf class in tests:

    $pdf = Mockery::mock('MikeHaertl\Phpwkhtmltopdf\Pdf');
    $pdf->shouldReceive('addPageHTML')->once()->with('Test');
    $pdf->shouldReceive('saveAs')->once()->with('test.pdf');
    
  5. Extensions: Extend the Pdf class for reusable configurations:

    class CustomPdf extends Pdf {
        public function __construct() {
            parent::__construct();
            $this->setOption('margin-top', '10mm');
            $this->setOption('margin-bottom', '10mm');
        }
    }
    
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui