xslain/html2media

Html2Media is a versatile Laravel package that allows users to convert HTML content into high-quality PDFs with options for either downloading or triggering a print dialog. Ideal for generating documents, invoices, and reports, this package includes configurable settings for file name, page orientat

1.0.0 2025-09-23 21:00 UTC

This package is auto-updated.

Last update: 2025-09-23 21:03:06 UTC


README

Html2Media is a powerful Laravel Livewire package that allows you to generate PDFs, preview documents, and directly print content from your application. πŸš€

πŸ“Œ Overview

The Html2Media package provides flexible Livewire components for your Laravel applications, enabling:

  • πŸ“‘ PDF Generation: Convert HTML to a PDF and download it.
  • πŸ–¨οΈ Direct Printing: Print HTML content directly from the application.
  • πŸ‘€ Document Preview: Preview the content before printing or exporting.

✨ Features

  • 🎨 Customizable File Naming: Define a custom name for the generated PDF.
  • πŸ” Preview & Print Options: Preview the content before printing or saving as a PDF.
  • πŸ“ Page Configuration: Adjust page orientation, size, margins, and scaling.
  • πŸ› οΈ Advanced PDF Options: Control page breaks, hyperlink inclusion, and more.
  • ⚑ Livewire Integration: Seamless integration with Livewire components and events.

πŸ”§ Installation

To install the package, simply run the following command:

composer require xslain/html2media

After installation, publish the assets:

php artisan vendor:publish --tag=html2media-assets

The Html2Media components will be automatically registered with Livewire.

πŸš€ Basic Usage

Method 1: Using the Livewire Component

You can use the Html2Media Livewire component directly in your Blade templates:

// In your Livewire component or controller
public function render()
{
    return view('your-view', [
        'record' => $this->record
    ]);
}
<!-- In your Blade template -->
@livewire('html2media', [
    'record' => $record,
    'content' => view('your-pdf-template', ['record' => $record])
])

Method 2: Using the Button Component

For a simple button that triggers PDF generation:

@livewire('html2media-button', [
    'record' => $record,
    'label' => 'Download Invoice',
    'content' => view('invoice-template', ['record' => $record])
])

Method 3: Creating Custom Livewire Components

Create your own Livewire component that uses the Html2Media trait:

<?php

namespace App\Http\Livewire;

use Livewire\Component;
use Xslain\Html2Media\Traits\HasHtml2MediaBase;

class InvoicePdfGenerator extends Component
{
    use HasHtml2MediaBase;

    public $invoice;

    public function mount($invoice)
    {
        $this->invoice = $invoice;
        
        // Configure the PDF settings
        $this->content(fn() => view('invoices.pdf', ['invoice' => $this->invoice]))
             ->filename('invoice-' . $this->invoice->id)
             ->orientation('portrait')
             ->format('a4')
             ->savePdf(true)
             ->print(true);
    }

    public function render()
    {
        return view('livewire.invoice-pdf-generator');
    }

    public function getElementId(): string
    {
        return 'invoice-' . $this->invoice->id;
    }

    public function downloadPdf()
    {
        $this->dispatch('triggerPrint', ...$this->getDispatchOptions('savePdf'));
    }

    public function printInvoice()
    {
        $this->dispatch('triggerPrint', ...$this->getDispatchOptions('print'));
    }
}

βš™οΈ Configuration Methods

Here's how you can customize your Html2Media components!

1. πŸ“‚ filename()

Set the name of the generated PDF file. ✍️

Usage:

$this->filename('my-custom-document')
  • 🏷️ Default: 'document.pdf'
  • πŸ”  Accepts: string or Closure

2. πŸ“„ pagebreak()

Define page break behavior. Customize how and where page breaks occur within the document. πŸ›‘

Usage:

$this->pagebreak('section', ['css', 'legacy'])
  • πŸ”„ Default: ['mode' => ['css', 'legacy'], 'after' => 'section']

  • πŸ› οΈ Accepts:

    • mode: Array of strings (['avoid-all', 'css', 'legacy'])
    • after: Element ID, class, tag, or * for all elements.
    • avoid: (Optional) Element ID, class, or tag to avoid page breaks.
  • πŸ“– More info on page breaks: here.

3. πŸ”„ orientation()

Set the page orientation for the PDF, either portrait or landscape. πŸ–ΌοΈ

Usage:

$this->orientation('landscape')
  • 🏷️ Default: 'portrait'
  • πŸ”  Accepts: string ('portrait', 'landscape') or Closure

4. πŸ“ format()

Define the format of the PDF, including standard sizes like A4 or custom dimensions. πŸ“

Usage:

$this->format('a4', 'mm')
// or custom dimensions
$this->format([210, 297], 'mm') // A4 dimensions
  • 🏷️ Default: 'a4'
  • πŸ”  Accepts: string (e.g., 'a4', 'letter') or array for custom dimensions, plus unit parameter

5. πŸ” scale()

Control the rendering quality of the PDF by adjusting the scale factor. πŸ“Š

Usage:

$this->scale(2)
  • 🏷️ Default: 2
  • πŸ”  Accepts: int or Closure

6. πŸ“ margin()

Set the margins for the PDF document. πŸ“

Usage:

$this->margin([10, 15, 10, 15]) // [top, right, bottom, left]
// or uniform margin
$this->margin(10)
  • 🏷️ Default: 0
  • πŸ”  Accepts: int (uniform margin) or array ([top, right, bottom, left]) or Closure

7. πŸ”— enableLinks()

Enable or disable PDF hyperlinks. When enabled, hyperlinks are automatically added on top of all anchor tags. 🌐

Usage:

$this->enableLinks(true)
  • 🏷️ Default: false
  • πŸ”  Accepts: bool or Closure

8. πŸ’» content()

Set the content for the document. Typically, you'll pass a Blade view for the content. πŸ“

Usage:

$this->content(fn() => view('invoice', ['record' => $this->record]))
  • πŸ”  Accepts: View, Htmlable, or Closure

🎨 Complete Example

Here's a complete example of a custom Livewire component with Html2Media:

<?php

namespace App\Http\Livewire;

use Livewire\Component;
use Xslain\Html2Media\Traits\HasHtml2MediaBase;

class ReportGenerator extends Component
{
    use HasHtml2MediaBase;

    public $report;

    public function mount($report)
    {
        $this->report = $report;
        
        // Configure all PDF settings
        $this->content(fn() => view('reports.pdf-template', ['report' => $this->report]))
             ->filename('report-' . $this->report->id)
             ->orientation('landscape') // Landscape for wide reports
             ->format('a4', 'mm') // A4 format with mm units
             ->scale(2) // High quality
             ->margin([10, 15, 10, 15]) // Custom margins
             ->enableLinks(true) // Enable clickable links
             ->pagebreak('section', ['css', 'legacy']) // Page breaks after sections
             ->savePdf(true) // Enable save PDF button
             ->print(true); // Enable print button
    }

    public function render()
    {
        return view('livewire.report-generator');
    }

    public function getElementId(): string
    {
        return 'report-' . $this->report->id;
    }
}

Corresponding Blade template (livewire/report-generator.blade.php):

<div>
    <div class="mb-4">
        <h3 class="text-lg font-semibold">{{ $report->title }}</h3>
        <p class="text-gray-600">Generate PDF or print this report</p>
    </div>

    <!-- Hidden content for PDF generation -->
    <div style="display: none">
        <main id="print-smart-content-{{ $this->getElementId() }}" style="color: black;" wire:ignore>
            {!! $this->getContent()?->toHtml() !!}
            <iframe style="display: none" id="print-smart-iframe-{{ $this->getElementId() }}"></iframe>
        </main>
    </div>
    
    <!-- Action buttons -->
    <div class="flex space-x-3">
        @if($this->isSavePdf())
            <button 
                wire:click="$dispatch('triggerPrint', {{ json_encode($this->getDispatchOptions('savePdf')) }})" 
                type="button"
                class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded"
            >
                πŸ“„ Download PDF
            </button>
        @endif

        @if($this->isPrint())
            <button 
                wire:click="$dispatch('triggerPrint', {{ json_encode($this->getDispatchOptions('print')) }})" 
                type="button"
                class="bg-green-500 hover:bg-green-700 text-white font-bold py-2 px-4 rounded"
            >
                πŸ–¨οΈ Print Report
            </button>
        @endif
    </div>
</div>

@push('scripts')
    <script src="{{ asset('vendor/html2media/js/es6-promise.min.js') }}"></script>
    <script src="{{ asset('vendor/html2media/js/jspdf.umd.min.js') }}"></script>
    <script src="{{ asset('vendor/html2media/js/html2canvas.min.js') }}"></script>
    <script src="{{ asset('vendor/html2media/js/html2pdf.min.js') }}"></script>
    <script src="{{ asset('vendor/html2media/js/html2media.js') }}"></script>
@endpush

⚑ Quick Examples

1. Simple PDF Download Button:

@livewire('html2media-button', [
    'label' => 'Download Invoice',
    'content' => view('invoices.pdf', ['invoice' => $invoice])
])

2. Multi-action Component:

@livewire('html2media', [
    'record' => $user,
    'content' => view('users.profile-pdf', ['user' => $user])
])

πŸ“‹ Requirements

  • PHP: ^8.1, ^8.2, or ^8.3
  • Laravel: ^10.0, ^11.0, or ^12.0
  • Livewire: ^3.0

🏁 Conclusion

The Html2Media package for Livewire makes it easy to generate PDFs, preview documents, and print content directly from your Laravel app. With flexible configuration options and seamless Livewire integration, you can tailor it to your specific needs, ensuring smooth document handling. ✨

We hope this documentation helps you get started quickly. πŸš€ Happy coding! πŸŽ‰

  • 🏷️ Default: 'document.pdf'
  • πŸ”  Accepts: string or Closure

2. πŸ“„ pagebreak()

Define page break behavior. Customize how and where page breaks occur within the document. πŸ›‘

Usage:

Html2MediaAction::make('print')
    ->pagebreak('section', ['css', 'legacy'])
  • πŸ”„ Default: ['mode' => ['css', 'legacy'], 'after' => 'section']

  • πŸ› οΈ Accepts:

    • mode: Array of strings (['avoid-all', 'css', 'legacy'])
    • after: Element ID, class, tag, or * for all elements.
    • avoid: (Optional) Element ID, class, or tag to avoid page breaks.
  • πŸ“– More info on page breaks: here.

3. πŸ”„ orientation()

Set the page orientation for the PDF, either portrait or landscape. πŸ–ΌοΈ

Usage:

Html2MediaAction::make('print')
    ->orientation('landscape')
  • 🏷️ Default: 'portrait'
  • πŸ”  Accepts: string ('portrait', 'landscape') or Closure

4. πŸ“ format()

Define the format of the PDF, including standard sizes like A4 or custom dimensions. πŸ“

Usage:

Html2MediaAction::make('print')
    ->format('letter', 'in')
  • 🏷️ Default: 'a4'
  • πŸ”  Accepts: string, array (e.g., [width, height]), or Closure

5. πŸ”— enableLinks()

Enable or disable automatic hyperlink conversion in the PDF. πŸ”—

Usage:

Html2MediaAction::make('print')
    ->enableLinks()
  • 🏷️ Default: false
  • πŸ”  Accepts: bool or Closure

6. πŸ”§ scale()

Adjust the scaling factor for HTML to PDF conversion. πŸ”

Usage:

Html2MediaAction::make('print')
    ->scale(2)
  • 🏷️ Default: 2
  • πŸ”  Accepts: int or Closure

7. πŸ–¨οΈ print()

Enable or disable the print button in the modal. πŸ–¨οΈ

Usage:

Html2MediaAction::make('print')
    ->print(true)
  • 🏷️ Default: true
  • πŸ”  Accepts: bool or Closure

8. πŸ‘οΈ preview()

Enable a preview option for the document content before printing or saving. πŸ‘€

Usage:

Html2MediaAction::make('print')
    ->preview()
  • 🏷️ Default: false
  • πŸ”  Accepts: bool or Closure

9. πŸ’Ύ savePdf()

Enable the option to directly save the content as a PDF. πŸ’Ύ

Usage:

Html2MediaAction::make('print')
    ->savePdf()
  • 🏷️ Default: false
  • πŸ”  Accepts: bool or Closure

10. βœ… requiresConfirmation()

Show a confirmation modal before performing the action. πŸ›‘

Usage:

Html2MediaAction::make('print')
    ->requiresConfirmation()
  • 🏷️ Default: true
  • πŸ”  Accepts: bool or Closure

11. πŸ’» content()

Set the content for the document. Typically, you’ll pass a Blade view for the content. πŸ“

Usage:

Html2MediaAction::make('print')
    ->content(fn($record) => view('invoice', ['record' => $record]))
  • πŸ”  Accepts: View, Htmlable, or Closure

🎨 Example Usage

Here’s a complete example of configuring the Html2MediaAction:

Html2MediaAction::make('print')
    ->scale(2)
    ->print() // Enable print option
    ->preview() // Enable preview option
    ->filename('invoice') // Custom file name
    ->savePdf() // Enable save as PDF option
    ->requiresConfirmation() // Show confirmation modal
    ->pagebreak('section', ['css', 'legacy'])
    ->orientation('portrait') // Portrait orientation
    ->format('a4', 'mm') // A4 format with mm units
    ->enableLinks() // Enable links in PDF
    ->margin([0, 50, 0, 50]) // Set custom margins
    ->content(fn($record) => view('invoice', ['record' => $record])) // Set content

This configuration will:

  • πŸ“„ Generate a PDF from the invoice Blade view.
  • πŸ–¨οΈ Allow users to preview and print the document.
  • πŸ’Ύ Enable saving as PDF and show a confirmation modal before executing.
  • πŸ“ Set A4 format with portrait orientation.
  • πŸ”— Enable links and set custom margins.

πŸ“Š Livewire Component Usage

You can use the Html2Media components in various ways throughout your Livewire application. Here are the available components:

// Use the full-featured component
@livewire('html2media', [
    'record' => $record,
    'content' => view('invoice', ['record' => $record])
])

// Or use the simple button component
@livewire('html2media-button', [
    'record' => $record,
    'label' => 'Download PDF',
    'content' => view('invoice', ['record' => $record])
])

This makes the package flexible and usable in various contexts throughout your Laravel application. 🌍

⚑ Quick Examples

  1. For direct printing:
@livewire('html2media-button', [
    'record' => $record,
    'label' => 'Print Invoice',
    'content' => view('invoice', ['record' => $record])
])

This will directly open the print dialog for the HTML content. πŸ–¨οΈ

  1. For saving as PDF:
@livewire('html2media-button', [
    'record' => $record,
    'label' => 'Download PDF',
    'content' => view('invoice', ['record' => $record])
])

This will save the HTML content as a PDF. πŸ’Ύ

🏁 Conclusion

The Html2Media package for Livewire makes it easy to generate PDFs, preview documents, and print content directly from your Laravel app. With flexible configuration options, you can tailor it to your specific needs, ensuring smooth document handling. ✨

We hope this documentation helps you get started quickly. πŸš€ Happy coding! πŸŽ‰