pontedilana / weasyprint-bundle
使用Twig/HTML模板轻松在Symfony中创建PDF。
2.2.0
2024-06-21 09:25 UTC
Requires
- php: 7.4.* || 8.0.* || 8.1.* || 8.2.* || 8.3.*
- pontedilana/php-weasyprint: ^1.0
- symfony/config: ^5.4 || ^6.3 || ^7.0
- symfony/dependency-injection: ^5.4 || ^6.3 || ^7.0
- symfony/http-foundation: ^5.4 || ^6.3 || ^7.0
- symfony/http-kernel: ^5.4 || ^6.3 || ^7.0
Requires (Dev)
- doctrine/annotations: ^1.11 || ^2.0
- friendsofphp/php-cs-fixer: ^3.13
- phpstan/extension-installer: ^1.1
- phpstan/phpstan: ^1.2
- phpstan/phpstan-phpunit: ^1.0
- phpstan/phpstan-symfony: ^1.0
- phpunit/phpunit: ^9.5
- symfony/framework-bundle: ^5.4 || ^6.3 || ^7.0
- symfony/phpunit-bridge: ^5.4 || ^6.3 || ^7.0
- symfony/validator: ^5.4 || ^6.3 || ^7.0
- symfony/yaml: ^5.4 || ^6.3 || ^7.0
README
PhpWeasyPrint 是一个PHP (7.4+)的 WeasyPrint PDF生成器的封装。它允许您从HTML字符串或URL生成PDF文件。
WeasyPrintBundle 为您的Symfony项目提供了一种简单的集成方式。
此包大量借鉴了 KnpLabs/KnpSnappyBundle,旨在成为一对一的替代品
安装
使用 composer,需要
composer require pontedilana/weasyprint-bundle
然后在您的内核中启用它(即将推出flex配方)
// config/bundles.php <?php return [ //... Pontedilana\WeasyprintBundle\WeasyprintBundle::class => ['all' => true], //... ];
配置
如果您需要更改二进制文件、实例选项,甚至禁用一个或两个服务,您可以通过配置来实现。
# config/packages/weasyprint.yaml weasyprint: pdf: enabled: true binary: /usr/local/bin/weasyprint options: []
如果您想更改默认的临时文件夹 sys_get_temp_dir()
,您可以使用
# config/packages/weasyprint.yaml weasyprint: temporary_folder: "%kernel.cache_dir%/weasyprint"
您还可以使用 process_timeout
配置生成器使用的超时时间
# config/packages/weasyprint.yaml weasyprint: process_timeout: 20 # In seconds
使用方法
该包注册了一个服务
weasyprint.pdf
服务允许您生成PDF文件。
从URL生成PDF文档
// @var Pontedilana\PhpWeasyPrint\Pdf $weasyprintPdf->generate('https://www.github.com', '/path/to/the/file.pdf');
从Twig视图生成PDF文档
// @var Pontedilana\PhpWeasyPrint\Pdf $weasyprintPdf->generateFromHtml( $this->renderView( 'frontend/product/pdf.html.twig', [ 'some' => $vars, ] ), '/path/to/the/file.pdf' );
从控制器中渲染PDF文档作为响应
use Pontedilana\WeasyprintBundle\WeasyPrint\Response\PdfResponse; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; class SomeController extends AbstractController { public function pdfAction(Pontedilana\PhpWeasyPrint\Pdf $weasyprintPdf) { $html = $this->renderView( 'frontend/product/pdf.html.twig', [ 'some' => $vars, ] ); return new PdfResponse( $weasyprintPdf->getOutputFromHtml($html), 'file.pdf' ); } }
渲染包含相对URL的PDF文档,如CSS文件或图像
use Pontedilana\WeasyprintBundle\WeasyPrint\Response\PdfResponse; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; class SomeController extends AbstractController { public function pdfAction(Pontedilana\PhpWeasyPrint\Pdf $weasyprintPdf) { $pageUrl = $this->generateUrl('homepage', [], true); // use absolute path! return new PdfResponse( $weasyprintPdf->getOutput($pageUrl), 'file.pdf' ); } }
致谢
WeasyPrintBundle 和 PhpWeasyPrint 由 Pontedilana 开发。
SnappyBundle 由 KnpLabs 开发。