pontedilana/weasyprint-bundle

使用Twig/HTML模板轻松在Symfony中创建PDF。

资助包维护!
endelwar
Ko Fi

安装次数: 409 357

依赖关系: 0

建议者: 0

安全: 0

星标: 32

关注者: 2

分支: 5

公开问题: 1

类型:symfony-bundle

2.2.0 2024-06-21 09:25 UTC

This package is auto-updated.

Last update: 2024-09-21 10:00:57 UTC


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 和 PhpWeasyPrintPontedilana 开发。
SnappyBundle 由 KnpLabs 开发。