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

Html2Media Laravel Package

torgodly/html2media

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require torgodly/html2media
    

    Publish the config (if needed):

    php artisan vendor:publish --provider="Torgodly\Html2Media\Html2MediaServiceProvider"
    
  2. 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>'),
        ];
    }
    
  3. 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.


Implementation Patterns

Core Workflows

  1. Dynamic HTML Rendering: Use closures or Blade views to generate HTML dynamically:

    ->html(fn ($record) => view('reports.invoice', ['data' => $record]))
    
  2. Integration with Filament:

    • Table Actions: Attach to rows for record-specific PDFs.
    • Resource Actions: Use in bulk or single-record contexts.
    • Modal Previews: Leverage Filament’s modal system for previews:
      ->modalHeading('Preview Invoice')
      ->modalWidth('5xl')
      
  3. Batch Processing: Generate PDFs for multiple records in a loop:

    foreach ($records as $record) {
        $pdf = app(Html2Media::class)
            ->setHtml($record->renderHtml())
            ->download();
    }
    
  4. 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();
    });
    

Integration Tips

  • Blade Templates: Use view() or @include for reusable HTML.
  • CSS/JS Injection: Inject custom stylesheets or scripts:
    ->css('css/custom.pdf.css')
    ->js('js/pdf.scripts.js')
    
  • Queue Jobs: Offload PDF generation to queues for long-running tasks:
    dispatch(new GeneratePdfJob($record));
    
    (Extend Html2Media to support job payloads.)

Gotchas and Tips

Pitfalls

  1. HTML Sanitization:

    • Unsanitized HTML may break PDF rendering. Use Str::of($html)->markdown() or Purifier for safety.
    • Fix: Sanitize input before passing to ->html().
  2. Complex Layouts:

    • Nested tables, multi-column layouts, or floating elements may render poorly in PDFs.
    • Tip: Use ->options(['defaultMediaType' => 'print']) to optimize for print.
  3. Memory Limits:

    • Large HTML payloads (e.g., reports with 1000+ rows) may hit PHP memory limits.
    • Solution: Stream output or chunk data:
      ->options(['stream' => true])
      
  4. Filament Modal Conflicts:

    • Modal previews may clash with Filament’s default styles.
    • Workaround: Override CSS in resources/css/filament/app.css:
      .filament-html2media-modal { all: unset; }
      

Debugging

  • 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.

Configuration Quirks

  1. Default Options: Override defaults globally in config/html2media.php:

    'default_options' => [
        'orientation' => 'landscape',
        'margin_top' => '20mm',
        'margin_bottom' => '20mm',
    ],
    
  2. Dynamic Filenames: Use closures for dynamic filenames:

    ->filename(fn ($record) => "invoice_{$record->id}.pdf")
    
  3. Headless Mode: Disable Filament UI entirely for API use:

    ->filament(false)
    ->download();
    

Extension Points

  1. 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.)

  2. Hooks: Add callbacks for pre/post-processing:

    ->beforeGenerate(fn ($html) => $html . '<div class="footer">Generated: ' . now() . '</div>')
    ->afterGenerate(fn ($pdf) => $pdf->setMetadata(['author' => 'MyApp']));
    
  3. Storage: Save PDFs to disk instead of downloading:

    ->store('storage/app/pdf/' . $filename)
    ->then(fn ($path) => $this->dispatchBrowserEvent('pdf-generated'));
    
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.
babenkoivan/elastic-client
innmind/static-analysis
innmind/coding-standard
datacore/hub-sdk
alengo/sulu-http-cache-bundle
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
imbo/imbo-coding-standard
visualbuilder/filament-lottie
servicioslineaonce/starter-kit
atomcoder/laravel-reorderable
irajul/filament-shadcn-theme
agtp/agtp-php
agtp/mod-php
centraldesktop/protobuf-php