目的/knp-snappy-bundle

通过将Twig/HTML模板转换为PDF和图像,轻松在Symfony2中创建。

安装: 15

依赖者: 0

建议者: 0

安全: 0

星标: 0

关注者: 1

分支: 143

类型:symfony-bundle

v1.4 2015-11-11 17:40 UTC

README

Snappy 是一个PHP (5.3+)的wkhtmltopdf转换工具包装器。它允许您使用webkit引擎从HTML文档生成PDF或图像文件。

KnpSnappyBundle 为您的Symfony项目提供了一个简单的集成。

Build Status

knpbundles.com

安装

使用 composer,添加

{
    "require": {
        "knplabs/knp-snappy-bundle": "~1.4"
    }
}

然后在您的内核中启用它

// app/AppKernel.php
public function registerBundles()
{
    $bundles = array(
        //...
        new Knp\Bundle\SnappyBundle\KnpSnappyBundle(),
        //...

配置

如果您需要更改二进制文件、更改实例选项或禁用一个或两个服务,您可以通过配置来完成。

# app/config/config.yml
knp_snappy:
    pdf:
        enabled:    true
        binary:     /usr/local/bin/wkhtmltopdf #"\"C:\\Program Files\\wkhtmltopdf\\bin\\wkhtmltopdf.exe\"" for Windows users
        options:    []
    image:
        enabled:    true
        binary:     /usr/local/bin/wkhtmltoimage #"\"C:\\Program Files\\wkhtmltopdf\\bin\\wkhtmltoimage.exe\"" for Windows users
        options:    []

如果您想更改默认的临时文件夹sys_get_temp_dir(),您可以使用

# app/config/config.yml
knp_snappy:
    temporary_folder: %kernel.cache_dir%/snappy

使用

该捆绑包注册了两个服务

  • knp_snappy.image服务允许您生成图像;
  • knp_snappy.pdf服务允许您生成PDF文件。

从URL生成图像

$container->get('knp_snappy.image')->generate('http://www.google.fr', '/path/to/the/image.jpg');

从URL生成PDF文档

$container->get('knp_snappy.pdf')->generate('http://www.google.fr', '/path/to/the/file.pdf');

从多个URL生成PDF文档

$container->get('knp_snappy.pdf')->generate(array('http://www.google.fr', 'http://www.knplabs.com', 'http://www.google.com'), '/path/to/the/file.pdf');

从Twig视图生成PDF文档

$this->get('knp_snappy.pdf')->generateFromHtml(
    $this->renderView(
        'MyBundle:Foo:bar.html.twig',
        array(
            'some'  => $vars
        )
    ),
    '/path/to/the/file.pdf'
);

从控制器以响应形式渲染图像

$html = $this->renderView('MyBundle:Foo:bar.html.twig', array(
    'some'  => $vars
));


return new Response(
    $this->get('knp_snappy.image')->getOutputFromHtml($html),
    200,
    array(
        'Content-Type'          => 'image/jpg',
        'Content-Disposition'   => 'filename="image.jpg"'
    )
);

从控制器以响应形式渲染PDF文档

$html = $this->renderView('MyBundle:Foo:bar.html.twig', array(
    'some'  => $vars
));

return new Response(
    $this->get('knp_snappy.pdf')->getOutputFromHtml($html),
    200,
    array(
        'Content-Type'          => 'application/pdf',
        'Content-Disposition'   => 'attachment; filename="file.pdf"'
    )
);

渲染包含相对URL(如CSS文件)的PDF文档

$pageUrl = $this->generateUrl('homepage', array(), true); // use absolute path!

return new Response(
    $this->get('knp_snappy.pdf')->getOutput($pageUrl),
    200,
    array(
        'Content-Type'          => 'application/pdf',
        'Content-Disposition'   => 'attachment; filename="file.pdf"'
    )
);

鸣谢

SnappyBundle和Snappy基于优秀的wkhtmltopdf。SnappyBundle由KnpLabs开发。