pontedilana/php-weasyprint
Composer 安装命令:
composer require pontedilana/php-weasyprint
包简介
PHP library allowing PDF generation from an url or a html page. Wrapper for Kozea/WeasyPrint.
关键字:
README 文档
README
PhpWeasyPrint is a PHP library allowing PDF generation from a URL or an HTML page. It's a wrapper for WeasyPrint, a smart solution helping web developers to create PDF documents, available everywhere Python runs.
You will have to download and install WeasyPrint to use PhpWeasyPrint (version 60 or greater is required).
This library is massively inspired by KnpLabs/snappy and aims to be a drop-in replacement: its GeneratorInterface mirrors Snappy's method contract (same method names and behaviour), though it lives in its own namespace and is strictly typed (string-only input, declared return types).
See "Differences with Snappy" section to see how the two differs
Requirements
- PHP 8.3, 8.4 or 8.5
- WeasyPrint 60 or greater
Installation using Composer
$ composer require pontedilana/php-weasyprint
Usage
Initialization
<?php require __DIR__ . '/vendor/autoload.php'; use Pontedilana\PhpWeasyPrint\Pdf; $pdf = new Pdf('/usr/local/bin/weasyprint'); // or you can do it in two steps $pdf = new Pdf(); $pdf->setBinary('/usr/local/bin/weasyprint');
Display the pdf in the browser
$pdf = new Pdf('/usr/local/bin/weasyprint'); header('Content-Type: application/pdf'); echo $pdf->getOutput('https://www.github.com');
Download the pdf from the browser
$pdf = new Pdf('/usr/local/bin/weasyprint'); header('Content-Type: application/pdf'); header('Content-Disposition: attachment; filename="file.pdf"'); echo $pdf->getOutput('https://www.github.com');
Generate local pdf file
$pdf = new Pdf('/usr/local/bin/weasyprint'); $pdf->generateFromHtml('<h1>Bill</h1><p>You owe me money, dude.</p>', '/tmp/bill-123.pdf');
Pass options to PhpWeasyPrint
// Type weasyprint -h to see the list of options $pdf = new Pdf('/usr/local/bin/weasyprint'); $pdf->setOption('encoding', 'utf8'); $pdf->setOption('media-type', 'screen'); $pdf->setOption('presentational-hints', true); $pdf->setOption('optimize-images', true); $pdf->setOption('stylesheet', ['/path/to/first-style.css', '/path/to/second-style.css']); $pdf->setOption('attachment', ['/path/to/image.png', '/path/to/logo.jpg']);
For options whose value is constrained to a fixed set, you can pass a backed enum instead of a raw string (it is converted to its scalar value automatically):
use Pontedilana\PhpWeasyPrint\Enum\MediaType; use Pontedilana\PhpWeasyPrint\Enum\PdfVariant; use Pontedilana\PhpWeasyPrint\Enum\PdfVersion; $pdf->setOption('media-type', MediaType::Screen); $pdf->setOption('pdf-variant', PdfVariant::PdfA3b); $pdf->setOption('pdf-version', PdfVersion::Pdf17);
Allowed URL schemes
Options that accept URLs (e.g. attachment) may be fetched server-side by the library.
To prevent SSRF and local file disclosure, only http and https URLs are fetched by
default; a value with any other scheme is treated as inline content instead of being
fetched. Local files keep working through their plain filesystem path.
If you need to fetch other schemes, pass an allow-list as the fourth constructor argument:
// Default: only http(s) URLs are fetched $pdf = new Pdf('/usr/local/bin/weasyprint'); $pdf->setOption('attachment', ['https://example.com/logo.png', '/path/to/local.png']); // Opt in to additional schemes (e.g. ftp) $pdf = new Pdf('/usr/local/bin/weasyprint', [], null, ['http', 'https', 'ftp']); // Or, with named arguments (PHP 8.0+) $pdf = new Pdf('/usr/local/bin/weasyprint', allowedSchemes: ['http', 'https', 'ftp']);
Command execution
The WeasyPrint process is executed from an argument array (new Process([...])), never through a shell. This makes command injection through option values, filenames or the binary path structurally impossible: there is no shell to interpret metacharacters, so no escaping is involved at execution time.
getCommand() and buildCommand() still return the command as a human-readable, shell-escaped string, but that representation is used only for logging and exception messages — it is not what gets executed.
Note for libraries extending
AbstractGenerator/executeCommand(), its signature changed fromexecuteCommand(string $command)toexecuteCommand(array $command). The binary executability check also moved fromgetEscapedBinary()to the newcheckBinary()method.
Reset options
Options can be reset to their initial values with resetOptions() method.
$pdf = new Pdf('/usr/local/bin/weasyprint'); // Set some options $pdf->setOption('media-type', 'screen'); // .. // Reset options $pdf->resetOptions();
Timeouts
A default timeout of 10 seconds is set for the WeasyPrint process to prevent orphaned or hanging processes.
This is a defensive measure that applies in most cases and helps ensure system stability.
You can change the timeout with the setTimeout() method:
$pdf = new Pdf('/usr/local/bin/weasyprint'); $pdf->setTimeout(30); // 30 seconds
The timeout can be disabled entirely using either of the following:
$pdf->setTimeout(null); // or $pdf->disableTimeout();
This is especially useful if you're running inside a queue worker, job runner, or other environments that already handle timeouts (e.g. Symfony Messenger, Laravel Queue, Supervisor).
Disabling the internal timeout in those cases avoids conflicts with higher-level timeout strategies.
Note:
ThesetTimeout()method affects both:
- how long the process is allowed to run before being forcibly stopped, and
- the
--timeoutoption passed to the WeasyPrint command-line tool.If you only want to disable WeasyPrint's own timeout (while keeping the execution time limit), use:
$pdf->setOption('timeout', null);
Differences with Snappy
Although PhpWeasyPrint and Snappy are interchangeable, there are a couple of differences between the two, due to WeasyPrint CLI API:
- WeasyPrint doesn't support multiple sources to be merged in one single output pdf, so only one input source (string or URL) is accepted in PhpWeasyPrint;
- WeasyPrint version >= 53 doesn't generate images, so image generation from HTML string or URL is possible only with WeasyPrint lower versions and an unsupported PhpWeasyPrint version (
Pontedilana\PhpWeasyPrint\Imagehas been successfully tested with Weasyprint 52.5 on PhpWeasyPrint 0.13.0).
Bugs & Support
If you found a bug please fill a detailed issue with all the following points. If you need some help, please at least provide a complete reproducer, so we could help you based on facts rather than assumptions.
- OS and its version
- WeasyPrint, its version and how you installed it
- A complete reproducer with relevant PHP and html/css/js code
If your reproducer is big, please try to shrink it. It will help everyone to narrow the bug.
Credits
PhpWeasyPrint has been originally developed by the Pontedilana dev team.
Snappy has been originally developed by the KnpLabs team.
pontedilana/php-weasyprint 适用场景与选型建议
pontedilana/php-weasyprint 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 1.24M 次下载、GitHub Stars 达 77, 最近一次更新时间为 2021 年 07 月 16 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「php」 「pdf」 「WeasyPrint」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 pontedilana/php-weasyprint 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 pontedilana/php-weasyprint 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 pontedilana/php-weasyprint 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Easily create PDF in Symfony by converting Twig/HTML templates.
A feature-rich WeasyPrint wrapper for generating PDFs from HTML and CSS, with support for PDF/A, PDF/UA, attachments, and optional Laravel integration.
WeasyPrint for Laravel
Provides TCPDF integration for Symfony
Alfabank REST API integration
A adapter for the mPDF print library
统计信息
- 总下载量: 1.24M
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 78
- 点击次数: 18
- 依赖项目数: 6
- 推荐数: 1
其他信息
- 授权协议: MIT
- 更新时间: 2021-07-16