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

xslain/html2media

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require xslain/html2media
    php artisan vendor:publish --tag=html2media-assets
    
    • Verify html2media config is published to config/html2media.php.
  2. Basic Livewire Usage:

    @livewire('html2media', [
        'content' => '<h1>Hello, PDF!</h1><p>This will be converted.</p>',
        'filename' => 'document.pdf',
        'options' => ['orientation' => 'landscape']
    ])
    
    • The component auto-registers; no manual binding required.
  3. First Use Case:

    • Generate a PDF from a Livewire component’s rendered HTML:
      // In your Livewire component
      public $htmlContent = '<h1>Invoice #123</h1><table>...</table>';
      
      public function downloadPdf()
      {
          return Html2Media::download($this->htmlContent, 'invoice_123.pdf');
      }
      

Implementation Patterns

Core Workflows

  1. Dynamic Content Conversion:

    • Use Livewire’s reactivity to update HTML before 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');
      }
      
  2. Preview + Print Integration:

    • Chain preview and print actions in a single component:
      @livewire('html2media', [
          'content' => $this->renderableHtml,
          'showPreview' => true, // Triggers modal preview
          'printOptions' => ['page-breaks' => true]
      ])
      
  3. Config-Driven Customization:

    • Override defaults in config/html2media.php:
      'default_options' => [
          'format' => 'A4',
          'margin-top' => 20,
          'margin-bottom' => 20,
          'scale' => 0.8,
      ],
      

Integration Tips

  • 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');
    

Gotchas and Tips

Pitfalls

  1. Asset Paths in HTML:

    • Ensure all CSS/JS paths in your HTML are absolute or use asset():
      <link href="{{ asset('css/styles.css') }}" rel="stylesheet">
      
    • Gotcha: Relative paths (e.g., /css/styles.css) may break in PDFs.
  2. Livewire Hydration:

    • Avoid converting Livewire’s internal markup (e.g., <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');
      
  3. Memory Limits:

    • Large HTML (e.g., tables with 1000+ rows) may hit PHP’s memory limit. Use chunking or pagination.
  4. CORS in Print Dialogs:

    • If printing fails in browsers, ensure your server allows X-Frame-Options or use:
      'print_options' => ['disable-frame-options' => true],
      

Debugging

  • 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).
    • For Puppeteer, ensure Chrome/Chromium is available.
  • Error Handling: Wrap calls in try-catch:

    try {
        return Html2Media::download($html, 'file.pdf');
    } catch (\Exception $e) {
        return back()->withError($e->getMessage());
    }
    

Extension Points

  1. Custom Drivers: Override the default PDF engine (e.g., switch to Dompdf):

    // config/html2media.php
    'driver' => 'dompdf',
    
  2. 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);
        });
    
  3. 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);
        }
    }
    
  4. Testing: Mock the package in tests:

    $this->mock(\Xslain\Html2Media\Facades\Html2Media::class)
        ->shouldReceive('download')
        ->once()
        ->andReturn('/fake/path.pdf');
    
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.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope