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

Htmltopdf Laravel Package

greenter/htmltopdf

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require greenter/htmltopdf
    

    Ensure wkhtmltopdf is installed on your system (Linux/Windows/macOS). Check wkhtmltopdf docs for installation instructions.

  2. Basic Usage:

    use Greenter\HtmlToPdf\HtmlToPdf;
    
    $html = '<h1>Hello, PDF!</h1><p>This is a test.</p>';
    $pdf = new HtmlToPdf();
    $pdf->setHtml($html);
    $pdf->setOptions(['orientation' => 'Portrait']);
    $pdf->saveAs('output.pdf');
    
  3. First Use Case: Convert a Blade template to PDF in a Laravel controller:

    use Greenter\HtmlToPdf\HtmlToPdf;
    use Illuminate\Support\Facades\View;
    
    public function generatePdf()
    {
        $html = View::make('invoice.template', ['data' => $invoiceData])->render();
        $pdf = new HtmlToPdf();
        $pdf->setHtml($html);
        $pdf->saveAs(storage_path('app/invoice.pdf'));
        return response()->download(storage_path('app/invoice.pdf'));
    }
    

Implementation Patterns

Workflows

  1. Dynamic PDF Generation: Use Blade templates for dynamic content:

    $html = View::make('report', ['user' => $user])->render();
    $pdf->setHtml($html);
    
  2. Streaming PDFs: Stream directly to the browser without saving to disk:

    $pdf->setHtml($html);
    $pdf->stream('invoice.pdf');
    
  3. Custom wkhtmltopdf Options: Pass options like margins, page size, or headers/footers:

    $pdf->setOptions([
        'margin-top'    => 20,
        'margin-right'  => 20,
        'margin-bottom' => 20,
        'margin-left'   => 20,
        'footer-html'   => '<div>Page <span class="page-number"></span></div>',
    ]);
    
  4. Queueing Long-Running Jobs: Use Laravel queues to avoid timeouts for complex PDFs:

    GeneratePdfJob::dispatch($html, $path)->onQueue('pdfs');
    

Integration Tips

  • Laravel Service Provider: Bind the package to the container for dependency injection:

    $this->app->bind(HtmlToPdf::class, function ($app) {
        return new HtmlToPdf();
    });
    
  • Configuration: Override default wkhtmltopdf path in config/services.php:

    'wkhtmltopdf' => [
        'binary' => '/usr/local/bin/wkhtmltopdf',
    ],
    
  • Testing: Mock the HtmlToPdf class in unit tests:

    $mock = Mockery::mock(HtmlToPdf::class);
    $mock->shouldReceive('setHtml')->once();
    $mock->shouldReceive('saveAs')->once();
    

Gotchas and Tips

Pitfalls

  1. wkhtmltopdf Binary Path:

    • If wkhtmltopdf isn’t in PATH, explicitly set the binary path in the constructor or config.
    • Error: Command not found or Failed to execute command.
  2. Memory Limits:

    • Complex HTML or large PDFs may hit memory limits. Use queue:work or increase memory_limit in php.ini.
  3. CSS/JS Dependencies:

    • External resources (e.g., Bootstrap, jQuery) must be embedded or hosted locally. Use file:// URLs or base64-encoded assets.
    • Fix: Prepend file:// to local paths or use asset() helper in Blade.
  4. Font Issues:

    • Custom fonts may not render. Ensure fonts are installed on the server or use @font-face with local paths.
  5. Deprecated Methods:

    • The package is outdated (last release 2018). Avoid relying on undocumented features.

Debugging

  • Logs: Enable verbose logging in wkhtmltopdf via options:

    $pdf->setOptions(['quiet' => false]);
    

    Check Laravel logs for wkhtmltopdf errors.

  • Dry Runs: Test with a simple HTML string before complex templates:

    $pdf->setHtml('<h1>Test</h1>')->saveAs('test.pdf');
    

Tips

  1. Caching: Cache generated PDFs to avoid reprocessing:

    if (!file_exists($cachedPath)) {
        $pdf->saveAs($cachedPath);
    }
    
  2. Headers/Footers: Use header-html/footer-html options for consistent branding:

    $pdf->setOptions([
        'header-html' => view('pdf.header')->render(),
        'footer-html' => view('pdf.footer')->render(),
    ]);
    
  3. Laravel Mix Integration: Process CSS/JS assets with Laravel Mix and embed them in Blade:

    <link href="{{ mix('css/pdf.css') }}" rel="stylesheet">
    <script src="{{ mix('js/pdf.js') }}"></script>
    
  4. Fallback for Missing wkhtmltopdf: Gracefully handle missing binary:

    try {
        $pdf->saveAs('output.pdf');
    } catch (\Exception $e) {
        Log::error('wkhtmltopdf not found: ' . $e->getMessage());
        return back()->withError('PDF generation failed.');
    }
    
  5. Performance: Disable JavaScript rendering for static content:

    $pdf->setOptions(['disable-javascript' => true]);
    
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky