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.
Installation Add the package via Composer:
composer require spipu/html2pdf
Ensure your server meets the requirements (PHP 8.0+, DOM extension, etc.).
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
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');
}
barryvdh/laravel-dompdf alternatives).Dynamic PDF Generation Use Blade views to render HTML before conversion:
$html = view('pdf.invoice', ['data' => $invoice])->render();
$pdf->writeHTML($html);
Streaming Large PDFs Avoid memory issues by streaming chunks:
$pdf->writeHTML($html);
$pdf->stream('large_report.pdf');
Custom Styling Override default CSS with inline styles or external sheets:
$pdf->writeHTML('<style>body { font-family: Arial; }</style>' . $html);
Headers/Footers
Use the setDefaultFont() and setFooter() methods:
$pdf->setDefaultFont('Arial');
$pdf->setFooter('Page {PAGE_NUM} of {PAGE_TOTAL}');
Response:
return response()->streamDownload(
fn () => $pdf->output(),
'report.pdf'
);
GeneratePdfJob).CSS Limitations
position: absolute, flexbox) may render poorly.Memory Leaks
Font Issues
setFont() or @font-face in CSS).DejaVu Sans).Encoding Problems
é, ñ) may corrupt.try-catch:
try {
$pdf->writeHTML($html);
} catch (\Exception $e) {
Log::error($e->getMessage());
}
Custom Templates
Extend Html2Pdf to add reusable methods:
class CustomPdf extends Html2Pdf {
public function addLogo($path) {
$this->writeHTML('<img src="' . asset($path) . '" width="100">');
}
}
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.
Laravel Service Provider Bind the converter to the container for dependency injection:
$this->app->bind(Html2Pdf::class, function () {
return new Html2Pdf(['mode' => 'utf-8']);
});
How can I help you explore Laravel packages today?