Installation:
composer require torgodly/html2media
Publish the config (if needed):
php artisan vendor:publish --provider="Torgodly\Html2Media\Html2MediaServiceProvider"
Basic Usage in Filament: Add the action to a Filament resource:
use Torgodly\Html2Media\Actions\Html2MediaAction;
public static function getActions(): array
{
return [
Html2MediaAction::make('print')
->label('Generate PDF')
->html(fn () => '<h1>Hello, PDF!</h1>'),
];
}
First Use Case:
Trigger the action in a Filament table or resource to generate a PDF from static HTML. Test with a simple <div> or Blade template.
Dynamic HTML Rendering: Use closures or Blade views to generate HTML dynamically:
->html(fn ($record) => view('reports.invoice', ['data' => $record]))
Integration with Filament:
->modalHeading('Preview Invoice')
->modalWidth('5xl')
Batch Processing: Generate PDFs for multiple records in a loop:
foreach ($records as $record) {
$pdf = app(Html2Media::class)
->setHtml($record->renderHtml())
->download();
}
API Endpoints: Expose PDF generation via API routes:
Route::post('/reports/{id}/pdf', function ($id) {
return app(Html2Media::class)
->setHtml(view('reports.detailed', ['id' => $id]))
->download();
});
view() or @include for reusable HTML.->css('css/custom.pdf.css')
->js('js/pdf.scripts.js')
dispatch(new GeneratePdfJob($record));
(Extend Html2Media to support job payloads.)HTML Sanitization:
Str::of($html)->markdown() or Purifier for safety.->html().Complex Layouts:
->options(['defaultMediaType' => 'print']) to optimize for print.Memory Limits:
->options(['stream' => true])
Filament Modal Conflicts:
resources/css/filament/app.css:
.filament-html2media-modal { all: unset; }
Log Output:
Enable debug mode in config/html2media.php:
'debug' => env('HTML2MEDIA_DEBUG', false),
Check Laravel logs for rendering errors.
Preview Issues:
Test previews in Chrome/Firefox (IE11 may render inconsistently). Use DevTools (Ctrl+Shift+I) to inspect the modal’s iframe.
Default Options:
Override defaults globally in config/html2media.php:
'default_options' => [
'orientation' => 'landscape',
'margin_top' => '20mm',
'margin_bottom' => '20mm',
],
Dynamic Filenames: Use closures for dynamic filenames:
->filename(fn ($record) => "invoice_{$record->id}.pdf")
Headless Mode: Disable Filament UI entirely for API use:
->filament(false)
->download();
Custom PDF Drivers: Extend the package to support additional drivers (e.g., DomPDF, Snappy):
// config/html2media.php
'driver' => 'snappy',
(Requires barryvdh/laravel-snappy or similar.)
Hooks: Add callbacks for pre/post-processing:
->beforeGenerate(fn ($html) => $html . '<div class="footer">Generated: ' . now() . '</div>')
->afterGenerate(fn ($pdf) => $pdf->setMetadata(['author' => 'MyApp']));
Storage: Save PDFs to disk instead of downloading:
->store('storage/app/pdf/' . $filename)
->then(fn ($path) => $this->dispatchBrowserEvent('pdf-generated'));
How can I help you explore Laravel packages today?