core23/dompdf-bundle

此包已被废弃,不再维护。作者建议使用 nucleos/dompdf-bundle 包。

此包为在 Symfony 中使用 dompdf 提供了一个包装器。

安装: 210,378

依赖者: 0

建议者: 0

安全: 0

星标: 38

关注者: 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

启用 Bundle

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

// config/bundles.php

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

配置 Bundle

# 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 许可证 下。