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

Html2Pdf Laravel Package

spipu/html2pdf

HTML2PDF converts HTML/CSS into PDF documents with a straightforward PHP API. Supports page setup, headers/footers, images, fonts and Unicode, tables, and basic CSS styling. Useful for invoices, reports, and print-ready exports in web apps.

View on GitHub
Deep Wiki
Context7

Getting Started

First Steps

  1. Installation Add the package via Composer:

    composer require spipu/html2pdf
    

    Ensure your server meets the requirements (PHP 8.0+, DOM extension, etc.).

  2. Basic Usage Include the autoloader and instantiate the converter:

    require_once __DIR__ . '/vendor/autoload.php';
    use Spipu\Html2Pdf\Html2Pdf;
    
    $html2pdf = new Html2Pdf();
    $html2pdf->writeHTML('<h1>Hello, PDF!</h1>');
    $html2pdf->output('output.pdf', 'D'); // 'D' forces download
    
  3. First Laravel Integration In a controller or service:

    use Spipu\Html2Pdf\Html2Pdf;
    
    public function generatePdf()
    {
        $html = view('pdf.template')->render();
        $pdf = new Html2Pdf();
        $pdf->writeHTML($html);
        return $pdf->output('invoice.pdf', 'D');
    }
    

Where to Look First

  • Official Docs (Quickstart, API reference).
  • Examples (Real-world use cases).
  • Laravel-Specific: Check for community wrappers (e.g., barryvdh/laravel-dompdf alternatives).

Implementation Patterns

Common Workflows

  1. Dynamic PDF Generation Use Blade views to render HTML before conversion:

    $html = view('pdf.invoice', ['data' => $invoice])->render();
    $pdf->writeHTML($html);
    
  2. Streaming Large PDFs Avoid memory issues by streaming chunks:

    $pdf->writeHTML($html);
    $pdf->stream('large_report.pdf');
    
  3. Custom Styling Override default CSS with inline styles or external sheets:

    $pdf->writeHTML('<style>body { font-family: Arial; }</style>' . $html);
    
  4. Headers/Footers Use the setDefaultFont() and setFooter() methods:

    $pdf->setDefaultFont('Arial');
    $pdf->setFooter('Page {PAGE_NUM} of {PAGE_TOTAL}');
    

Integration Tips

  • Laravel Responses: Return PDFs via Response:
    return response()->streamDownload(
        fn () => $pdf->output(),
        'report.pdf'
    );
    
  • Queue Jobs: Offload PDF generation to queues (e.g., GeneratePdfJob).
  • Caching: Cache rendered HTML if generating identical PDFs frequently.

Gotchas and Tips

Pitfalls

  1. CSS Limitations

    • Complex CSS (e.g., position: absolute, flexbox) may render poorly.
    • Fix: Use tables or inline styles for critical layouts.
  2. Memory Leaks

    • Large HTML inputs can exhaust memory.
    • Fix: Stream output or break HTML into chunks.
  3. Font Issues

    • Custom fonts require embedding (use setFont() or @font-face in CSS).
    • Fix: Preload fonts or use system fonts (e.g., DejaVu Sans).
  4. Encoding Problems

    • Special characters (e.g., é, ñ) may corrupt.
    • Fix: Ensure UTF-8 encoding in HTML and PDF headers.

Debugging

  • Inspect Rendered HTML: Use browser dev tools to validate HTML/CSS before conversion.
  • Log Errors: Wrap calls in try-catch:
    try {
        $pdf->writeHTML($html);
    } catch (\Exception $e) {
        Log::error($e->getMessage());
    }
    

Extension Points

  1. Custom Templates Extend Html2Pdf to add reusable methods:

    class CustomPdf extends Html2Pdf {
        public function addLogo($path) {
            $this->writeHTML('<img src="' . asset($path) . '" width="100">');
        }
    }
    
  2. Hooks for Post-Processing Use output() callbacks to modify PDFs (e.g., add signatures):

    $pdf->output('file.pdf', 'S'); // 'S' saves to file
    // Manually add annotations with TCPDF or other libraries.
    
  3. Laravel Service Provider Bind the converter to the container for dependency injection:

    $this->app->bind(Html2Pdf::class, function () {
        return new Html2Pdf(['mode' => 'utf-8']);
    });
    
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.
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
spatie/mailcoach-vapor