定制 hkwise/laravel-weasyprint 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

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

hkwise/laravel-weasyprint

Composer 安装命令:

composer require hkwise/laravel-weasyprint

包简介

A Laravel wrapper for WeasyPrint to generate PDFs

README 文档

README

Latest Stable Version Total Downloads

A Laravel wrapper for WeasyPrint, a powerful tool for generating PDFs. This package provides an easy-to-use interface for generating, saving, downloading, and displaying PDFs in Laravel applications.

About WeasyPrint

WeasyPrint is a Python-based library that converts HTML and CSS documents into PDFs. It supports modern web standards, making it ideal for generating high-quality PDFs from complex HTML and CSS.

Key Features of WeasyPrint:

  • High-Quality Output: Supports modern CSS features like Flexbox, Grid, and more.
  • Cross-Platform: Works on Linux, macOS, and Windows (with some setup).
  • Open Source: Free to use and actively maintained.

Features

This Laravel package provides seamless integration with WeasyPrint, enabling easy PDF generation with various options:

  • 📄Generate PDFs from Blade views, HTML strings, files, or URLs.
  • 💾 Save PDFs to disk or display them directly to the browser.
  • 📥 Download PDFs with custom filenames.
  • Set custom options for WeasyPrint (e.g., metadata, attachments).
  • Timeout configuration for long-running processes.
  • 🔧 Disable/Enable the package dynamically via configuration.

With these features, generating and managing PDFs in your Laravel project becomes effortless! 🚀

Prerequisites

Before using this package, ensure the following dependencies are installed:

  • Python: WeasyPrint requires Python 3 or higher to work correctly.
  • WeasyPrint: Install WeasyPrint using pip or a package manager.

Installation

1. Install the package via Composer:
composer require hkwise/laravel-weasyprint
2. Publish the Configuration File (Optional)
php artisan vendor:publish --provider="HKWise\WeasyPrint\WeasyPrintServiceProvider"
3. Install WeasyPrint
Linux

The easiest way to install WeasyPrint on Linux is to use the package manager of your distribution.

  • Debian/Ubuntu

Install WeasyPrint using apt:

sudo apt install weasyprint
  • Fedora

Install WeasyPrint using dnf:

sudo dnf install weasyprint
  • Archlinux

Install WeasyPrint using pacman:

sudo pacman -S python-weasyprint

Alternatively, install via pip:

pip install weasyprint
macOS

The easiest way to install WeasyPrint on macOS is to use Homebrew:

brew install weasyprint
Windows

To use WeasyPrint on Windows, the easiest way is to use the executable of the latest release.

If you want to use WeasyPrint as a Python library, you’ll have to follow a few extra steps. Please read this carefully.

The first step is to install the latest version of Python.

When Python is installed, you have to install Pango and its dependencies. The easiest way to install these libraries is to use MSYS2. Here are the steps you have to follow:

  • Install MSYS2 keeping the default options.
  • After installation, in MSYS2’s shell, execute pacman -S mingw-w64-x86_64-pango.
  • Close MSYS2’s shell.

You can then launch a Windows command prompt by clicking on the Start menu, typing cmd and clicking the “Command Prompt” icon. Install WeasyPrint in a virtual environment using pip:

python3 -m venv venv
venv\Scripts\activate.bat
python3 -m pip install weasyprint
python3 -m weasyprint --info

For more detailed installation instructions, visit the WeasyPrint Documentation.

Customizing the Configuration

You can modify the package settings in config/weasyprint.php:

  • Enable/Disable Package: Set 'enabled' => false, to disable WeasyPrint without removing it.

  • Change Default Save Path: Update 'default_path' => storage_path('app/custom-pdfs'), to save PDFs in a different directory.

  • Adjust Timeout: Modify 'timeout' => 120, to increase the maximum execution time.

This configuration ensures flexibility while using WeasyPrint in your Laravel application. 🚀

Usage

1. Generate PDF from a Blade View and Download
use HKWise\WeasyPrint\Facades\WeasyPdf;

$data = ['name' => 'John Doe'];
return WeasyPdf::loadView('pdf.invoice', $data)->download('invoice.pdf');
2. Generate PDF from HTML and Save to Disk
use HKWise\WeasyPrint\Facades\WeasyPdf;

WeasyPdf::loadHTML('<h1>Hello, World!</h1>')->save(storage_path('app/example.pdf'));
3. Generate PDF from a URL and Display in the browser
use HKWise\WeasyPrint\Facades\WeasyPdf;

return WeasyPdf::generate('https://weasyprint.org')->inline();
4. Generate PDF from a File and Download
use HKWise\WeasyPrint\Facades\WeasyPdf;

return WeasyPdf::loadFile(public_path('myfile.html'))->download('myfile.pdf');
5. You can chain multiple methods together. For example, you can save the PDF to disk first, then download it:
use HKWise\WeasyPrint\Facades\WeasyPdf;

return WeasyPdf::loadHtml('<h1>Hello, WeasyPrint!</h1>')
    ->save(storage_path('app/pdfs/myfile.pdf'))
    ->download('myfile.pdf');
6. Set Custom Options

You can pass additional WeasyPrint options using the setOptions method:

use HKWise\WeasyPrint\Facades\WeasyPdf;

return WeasyPdf::loadHTML('<h1>Test</h1>')
    ->setOptions([
        'custom-metadata' => 'metadata.json',
        'attachment' => ['note.txt', 'photo.jpg'],
    ])
    ->download('document.pdf');

Adjust Document Dimensions

This package does not support setting page size or document margins via configuration options. Instead, you must define these settings using the CSS @page at-rule in your HTML or stylesheets.

Example: Set Page Size and Margins

@page {
  size: Letter; /* Change from the default size of A4 */
  margin: 3cm; /* Set margin on each page */
}

There is much more which can be achieved with the @page at-rule, such as page numbers, headers, etc. Read more about the page at-rule.

Customizing the Facade Alias

By default, the Facade is registered as WeasyPdf. If you want to use a different alias (e.g., WPdf), you can manually register it in config/app.php:

'aliases' => [
    // Other aliases
    'WPdf' => HKWise\WeasyPrint\Facades\WeasyPdf::class,
],

After updating the alias, you can use WPdf instead of WeasyPdf:

use WPdf;

return WPdf::loadHTML('<h1>Hello, World!</h1>')->inline();

Alternatively, you can register both aliases:

'aliases' => [
    // Other aliases
    'WeasyPdf' => HKWise\WeasyPrint\Facades\WeasyPdf::class,
    'WPdf' => HKWise\WeasyPrint\Facades\WeasyPdf::class,
],

Now, you can use either WeasyPdf or WPdf:

use WeasyPdf;
use WPdf;

// Both will work
return WeasyPdf::loadHTML('<h1>Hello, World!</h1>')->inline();
return WPdf::loadHTML('<h1>Hello, World!</h1>')->inline();

Methods

Method Description
loadView Load a Blade view with data.
loadHTML Load raw HTML content.
loadFile Load HTML content from a file.
generate Fetch HTML content from a URL.
setOptions Set additional WeasyPrint options (e.g., --custom-metadata, --attachment).
save Save the PDF to a specified path (or default path).
download Download the PDF with a specified filename.
inline Display the PDF in the browser.

Troubleshooting

1. WeasyPrint Command Not Found

  • Ensure WeasyPrint is installed on your system:
pip install weasyprint
  • On Linux (Debian/Ubuntu), you can install WeasyPrint using:
sudo apt install weasyprint

2. Timeout Errors

  • Increase the timeout value in config/weasyprint.php if PDF generation takes longer than expected.

3. Local Environment Issues

This package may not work properly in local environments on Windows or macOS due to missing system dependencies for WeasyPrint. If you face issues while generating PDFs locally, consider disabling the package in non-production environments.

You can achieve this by modifying the enabled option in the configuration file (config/weasyprint.php):

'enabled' => app()->environment(['production', 'prod']),

This ensures the package is only enabled in production environments.

How It Works

Laravel’s app()->environment() method checks the current application environment based on the APP_ENV value set in your .env file.

For example, if your .env file contains:

APP_ENV=local

Then app()->environment(['production', 'prod']) will return false, disabling the package. However, in a production environment:

APP_ENV=production

app()->environment(['production', 'prod']) will return true, enabling the package.

Contributing

Contributions are welcome! Please open an issue or submit a pull request on GitHub.

License

This package is open-source software licensed under the MIT License.

Credits

hkwise/laravel-weasyprint 适用场景与选型建议

hkwise/laravel-weasyprint 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 20 次下载、GitHub Stars 达 3, 最近一次更新时间为 2025 年 03 月 16 日, 在 PHP 生态内属于活跃度较高的组件。

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

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

围绕 hkwise/laravel-weasyprint 我们能提供哪些服务?
定制开发 / 二次开发

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

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

GitHub 信息

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

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-03-16