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
Requires
- php: ^8.1|^8.2|^8.3
- illuminate/contracts: ^10.0|^11.0|^12.0
- illuminate/support: ^10.0|^11.0|^12.0
- livewire/livewire: ^3.0
- spatie/laravel-package-tools: ^1.13
Requires (Dev)
- orchestra/testbench: ^8.0|^9.0|^10.0
- phpunit/phpunit: ^9.0|^10.0|^11.0
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
orClosure
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'
) orClosure
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'
) orarray
for custom dimensions, plusunit
parameter
5. π scale()
Control the rendering quality of the PDF by adjusting the scale factor. π
Usage:
$this->scale(2)
- π·οΈ Default:
2
- π Accepts:
int
orClosure
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) orarray
([top, right, bottom, left]) orClosure
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
orClosure
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
, orClosure
π¨ 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
orClosure
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'
) orClosure
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]
), orClosure
5. π enableLinks()
Enable or disable automatic hyperlink conversion in the PDF. π
Usage:
Html2MediaAction::make('print') ->enableLinks()
- π·οΈ Default:
false
- π Accepts:
bool
orClosure
6. π§ scale()
Adjust the scaling factor for HTML to PDF conversion. π
Usage:
Html2MediaAction::make('print') ->scale(2)
- π·οΈ Default:
2
- π Accepts:
int
orClosure
7. π¨οΈ print()
Enable or disable the print button in the modal. π¨οΈ
Usage:
Html2MediaAction::make('print') ->print(true)
- π·οΈ Default:
true
- π Accepts:
bool
orClosure
8. ποΈ preview()
Enable a preview option for the document content before printing or saving. π
Usage:
Html2MediaAction::make('print') ->preview()
- π·οΈ Default:
false
- π Accepts:
bool
orClosure
9. πΎ savePdf()
Enable the option to directly save the content as a PDF. πΎ
Usage:
Html2MediaAction::make('print') ->savePdf()
- π·οΈ Default:
false
- π Accepts:
bool
orClosure
10. β
requiresConfirmation()
Show a confirmation modal before performing the action. π
Usage:
Html2MediaAction::make('print') ->requiresConfirmation()
- π·οΈ Default:
true
- π Accepts:
bool
orClosure
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
, orClosure
π¨ 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
andprint
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
- 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. π¨οΈ
- 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! π