承接 xslain/html2media 相关项目开发

从需求分析到上线部署,全程专人跟进,保证项目质量与交付效率

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

xslain/html2media

Composer 安装命令:

composer require 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

README 文档

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! 🎉

xslain/html2media 适用场景与选型建议

xslain/html2media 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 1 次下载、GitHub Stars 达 0, 最近一次更新时间为 2025 年 09 月 23 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「pdf」 「invoice」 「documents」 「laravel」 「reporting」 「printing」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 xslain/html2media 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 xslain/html2media 我们能提供哪些服务?
定制开发 / 二次开发

基于 xslain/html2media 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 1
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 25
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 0
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-09-23