January 19, 2014

January 19, 2014
In this article, we are going to discuss about How to create PDF from HTML in symfony 2 framework using Snappy bundle. Snappy is a Bundle that is used for the conversion utility wkhtmltopdf in PHP 5.3, allows us to generate PDF file from html document. KnpSnappyBundle provide integration with Symfony2 Framework.

To be able to do the conversion, we first used a binary download wkhtmltopdf here:
http://code.google.com/p/wkhtmltopdf/. Once download the binary file, then we can install. After we install, we can integrate with Symfony2 quickly and easily.

First, we used the configuration:

# app/config/config.yml
knp_snappy:
    pdf:
        enabled:    true
        binary:     C:\wkhtmltopdf\wkhtmltopdf.exe #path to binary wkhtmltopdf
        options:    []
       
Then, we download the vendor from the git repository

git submodule add https://github.com/knplabs/snappy.git vendor/snappy

Download the bundle from the below URL

git submodule add https://github.com/knplabs/KnpSnappyBundle.git vendor/bundles/Knp/Bundle/SnappyBundle

List the autoload by using the below code

$loader->registerNamespaces(array(
//................SNAPPY..........//
'Knp'                        => __DIR__.'/../vendor/bundles',
'Knp\\Snappy'                => __DIR__.'/../vendor/snappy/src'
//-----------------------------------------------
));

Add the Kernel using the below code

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

Finally test the above by using the below code

$html = $this->renderView('Testmodule:Test:index.html.twig', array(
  'some'  => 'somethingvalue'
));

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

);

0 comments:

Post a Comment