Installation:
composer require xslain/html2media
php artisan vendor:publish --tag=html2media-assets
html2media config is published to config/html2media.php.Basic Livewire Usage:
@livewire('html2media', [
'content' => '<h1>Hello, PDF!</h1><p>This will be converted.</p>',
'filename' => 'document.pdf',
'options' => ['orientation' => 'landscape']
])
First Use Case:
// In your Livewire component
public $htmlContent = '<h1>Invoice #123</h1><table>...</table>';
public function downloadPdf()
{
return Html2Media::download($this->htmlContent, 'invoice_123.pdf');
}
Dynamic Content Conversion:
// Livewire component
public $userData;
public $invoiceHtml;
public function mount()
{
$this->invoiceHtml = view('invoices.partial', ['data' => $this->userData])->render();
}
public function generatePdf()
{
return Html2Media::download($this->invoiceHtml, 'invoice_'.$this->userData['id'].'.pdf');
}
Preview + Print Integration:
@livewire('html2media', [
'content' => $this->renderableHtml,
'showPreview' => true, // Triggers modal preview
'printOptions' => ['page-breaks' => true]
])
Config-Driven Customization:
config/html2media.php:
'default_options' => [
'format' => 'A4',
'margin-top' => 20,
'margin-bottom' => 20,
'scale' => 0.8,
],
Livewire Events:
Listen for pdf-generated or print-triggered events to log actions or update UI:
protected $listeners = ['pdf-generated' => 'handlePdfGenerated'];
public function handlePdfGenerated($filename)
{
$this->dispatch('alert', type: 'success', message: "PDF saved: $filename");
}
Blade Templates: Pass Blade views directly:
Html2Media::download(view('reports.detailed', ['data' => $report])->render(), 'report.pdf');
Queue Jobs: Offload PDF generation to a queue for large documents:
GeneratePdfJob::dispatch($html, 'filename.pdf')->onQueue('pdfs');
Asset Paths in HTML:
asset():
<link href="{{ asset('css/styles.css') }}" rel="stylesheet">
/css/styles.css) may break in PDFs.Livewire Hydration:
<div wire:key>). Use ->render() on child views:
// ❌ Avoid
Html2Media::download($this->render(), 'page.pdf');
// ✅ Do this
Html2Media::download(view('child.view')->render(), 'page.pdf');
Memory Limits:
CORS in Print Dialogs:
X-Frame-Options or use:
'print_options' => ['disable-frame-options' => true],
Inspect Generated HTML: Log the HTML before conversion to catch rendering issues:
\Log::debug('PDF HTML:', ['content' => $this->htmlContent]);
Check Underlying Libraries: The package uses wkhtmltopdf or Puppeteer. Verify:
wkhtmltopdf is installed and in PATH (if using the default driver).Error Handling: Wrap calls in try-catch:
try {
return Html2Media::download($html, 'file.pdf');
} catch (\Exception $e) {
return back()->withError($e->getMessage());
}
Custom Drivers: Override the default PDF engine (e.g., switch to Dompdf):
// config/html2media.php
'driver' => 'dompdf',
Post-Processing:
Hook into the pdf-generated event to modify the PDF:
Html2Media::download($html, 'file.pdf')
->then(function ($path) {
// Add watermark, sign, etc.
$this->addWatermark($path);
});
Livewire Properties: Extend the component by adding custom properties:
// app/Http/Livewire/CustomHtml2Media.php
class CustomHtml2Media extends \Xslain\Html2Media\Livewire\Html2Media
{
public $customOption = 'default';
public function generateWithCustomOption()
{
$options = $this->options + ['custom' => $this->customOption];
return parent::download($this->content, 'file.pdf', $options);
}
}
Testing: Mock the package in tests:
$this->mock(\Xslain\Html2Media\Facades\Html2Media::class)
->shouldReceive('download')
->once()
->andReturn('/fake/path.pdf');
How can I help you explore Laravel packages today?