typesetsh/pdf-bundle

此包提供了一个用于使用typeset.sh pdf引擎的包装器。

17.0.2 2024-07-25 16:55 UTC

README

此包是typeset.sh pdf引擎的简单包装器。

Typeset.sh是一个允许将内容渲染为PDF的CSS/HTML布局引擎。

安装

打开命令控制台,进入您的项目目录,并执行以下命令以下载此包的最新稳定版本

composer require typesetsh/pdf-bundle

启用包

然后,将此包添加到项目中config/bundles.php文件的已注册包列表中,以启用包

return [
    // [...]
    Typesetsh\PdfBundle\TypesetshPdfBundle::class => ['all' => true],
];

使用

将视图渲染为PDF。您可以使用抽象控制器将twig视图渲染为PDF。

<?php

namespace App\Controller;

use Symfony\Component\HttpFoundation\HeaderUtils;
use Typesetsh\PdfBundle;

class TestController extends PdfBundle\Controller\AbstractController
{
    public function printOrder()
    {
        $order = new \stdClass();

        return $this->pdf(
            'pdf/invoice.html.twig',
            ['order' => $order],
            'test.pdf',
            HeaderUtils::DISPOSITION_INLINE
        );
    }
}

或者,您也可以使用依赖注入来获取PDF生成,并按您希望的方式处理它。

<?php

use Typesetsh\PdfBundle\PdfGenerator;

class PrintService
{
    /** @var PdfGenerator */
    private $pdfGenerator;

    public function __construct(PdfGenerator $pdfGenerator)
    {
        $this->pdfGenerator = $pdfGenerator;
    }

    public function execute()
    {
        $html = '...';

        $result = $this->pdfGenerator->render($html);
        $result->toFile('./somefile.pdf');
        $result->asString();

    }
}

配置

# /config/packages/typesetsh_pdf.yaml

typesetsh_pdf:
  # List of allowed directories to load external resources (css, images, fonts,...)
  allowed_directories:
    - '%kernel.project_dir%/public'

  # Default base dir - Used when view URIs use relative path /
  base_dir: '%kernel.project_dir%/public'

  http:
    # Allow to download external resources via http(s)
    allow: false
    # Cache dir fir files downloaded via http(s)
    cache_dir: '%kernel.cache_dir%/typesetsh'
    # Maximum file size in bytes to download via http(s)
    download_limit: 1048576
    # Timeout in seconds when downloading files
    timeout: 5

安全

请确保仅白名单不包含任何敏感信息的目录,以防止数据泄露。如果您的模板正确转义,这应该永远不会成为问题,但总是很好忽略任何未在allowed_directories中白名单的资源。

默认情况下,仅允许/public目录。如果您想添加其他目录,您必须首先将其白名单。

HTML模板示例

支持许多CSS功能。有关更多详细信息,请参阅typeset.sh和示例。

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>test</title>
        <style>
            @page {
                size: A4;
                margin: 10mm 20mm;
            }
            @font-face {
                font-family: "my font";
                src: url("/fonts/my-font.otf");
                font-weight: 400;
            }
            @font-face {
                font-family: "my font";
                src: url("/fonts/my-font.otf");
                font-weight: 800;
            }
            html {
                font-family: "my font", serif;
                font-size: 12pt;
            }
        </style>
    </head>
    <body>
        <h1>Your lucky number is {{ number }}</h1>
        <p>Some text....</p>
    </body>
</html>

许可

此包受MIT许可证的约束。

然而,它需要一个typeset.sh的版本才能工作。