nucleos/dompdf-bundle

此包提供了在 symfony 中使用 dompdf 的包装器。

安装数: 291,857

依赖者: 2

建议者: 0

安全性: 0

星标: 39

关注者: 3

分支: 12

开放问题: 5

类型:symfony-bundle

4.3.0 2024-08-14 16:24 UTC

README

Latest Stable Version Latest Unstable Version License

Total Downloads Monthly Downloads Daily Downloads

Continuous Integration Code Coverage Type Coverage

此包提供了在 Symfony 中使用 dompdf 的包装器。

安装

打开命令行,进入你的项目目录,然后执行以下命令以下载此包的最新稳定版本

composer require nucleos/dompdf-bundle

启用包

然后,通过将其添加到项目 config/bundles.php 文件中注册的包列表来启用该包

// config/bundles.php

return [
    // ...
    Nucleos\DompdfBundle\NucleosDompdfBundle::class => ['all' => true],
];

配置包

# config/packages/nucleos_dompdf.yaml

nucleos_dompdf:
    defaults:
        defaultFont: 'helvetica'
        # See https://github.com/dompdf/dompdf/wiki/Usage#options for available options

使用

每次需要将 HTML 页面转换为 PDF 时,请使用服务依赖注入

use Nucleos\DompdfBundle\Factory\DompdfFactoryInterface;
use Nucleos\DompdfBundle\Wrapper\DompdfWrapperInterface;

final class MyService
{
    public function __construct(DompdfFactoryInterface $factory)
    {
        $this->factory = $factory;
    }

    public function render()
    {
        // ...
        /** @var Dompdf\Dompdf $dompdf */
        $dompdf = $this->factory->create();
        // Or pass an array of options:
        $dompdf = $this->factory->create(['chroot' => '/home']);
        // ...
    }
}

final class MyOtherService
{
    public function __construct(DompdfWrapperInterface $wrapper)
    {
        $this->wrapper = $wrapper;
    }

    public function stream()
    {
        // ...
        $html = '<h1>Sample Title</h1><p>Lorem Ipsum</p>';

        /** @var Symfony\Component\HttpFoundation\StreamedResponse $response */
        $response = $this->wrapper->getStreamResponse($html, "document.pdf");
        $response->send();
        // ...
    }

    public function binaryContent()
    {
        // ...
        return $this->wrapper->getPdf($html);
        // ...
    }
}

使用 Twig 渲染 PDF

如果您使用 Twig 创建内容,请确保使用 renderView() 而不是 render()。否则,您可能在 PDF 中打印以下 HTTP 标头

HTTP/1.0 200 OK Cache-Control: no-cache

$html = $this->renderView('my_pdf.html.twig', array(
    // ...
));
$this->wrapper->getStreamResponse($html, 'document.pdf');

使用 asset() 链接资源

首先,确保您的 chroot 设置正确,且 isRemoteEnabled 为 true。

# config/packages/nucleos_dompdf.yaml

nucleos_dompdf:
    defaults:
        chroot: '%kernel.project_dir%/public/assets'
        isRemoteEnabled: true

其次,使用 {{ absolute_url( asset() ) }}

<img src={{ absolute_url( asset('assets/example.jpg') ) }}>

事件

dompdf 包装器在创建 PDF 时会派发事件,以便方便地获取内部的 dompdf 实例。

  • dompdf.outputgetPdf() 中派发
  • dompdf.streamstreamHtml() 中派发

有关更多信息,请参阅 Symfony 事件和事件监听器

许可协议

此包受 MIT 许可协议 的约束。