Lucas Courot

How to generate a pdf document with Symfony2

Posted on by

The tool

There is a Symfony2 bundle to help you generate PDF files called KnpSnappyBundle. It's based on Snappy. Snappy is a PHP (5.3+) wrapper for the wkhtmltopdf conversion utility. It allows you to generate either pdf or image files from your html documents, using the webkit engine.

Generate a pdf document from a twig view

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

The config

First of all, you have to install wkhtmltopdf. Then install xvfb to not have the x server error: sudo aptitude install xvfb wkhtmltopdf.

Append the config below to your config file.

# app/config/config.yml
knp_snappy:
    pdf:
        enabled:    true
        binary:     "xvfb-run -a -s \"-screen 0 640x480x16\" -e %kernel.root_dir%/logs/snappy.log wkhtmltopdf"
        options:    []
    image:
        enabled:    false
        binary:     /usr/local/bin/wkhtmltoimage
        options:    []

I had to change the default binary parameter so the tool works correctly xvfb-run -a -s "-screen 0 640x480x16" wkhtmltopdf.

# man xvfb-run
-a, --auto-servernum
        Try to get a free server number, starting at 99, or the argument to --server-num.

That's all!

See the other articles published in Symfony .