Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bad characters when generating pdf file with Knp Snappy

I am using Symfony2. When the pdf file is generated using this code :

public function printAction($id)
    {
        // initialiser $demande
        $html = $this->renderView('PFETimeBundle:Demande:print.html.twig',
            array('demande'=> $demande)
        );

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

I get this content (french characters appear in bad characters) : enter image description here

like image 312
mehdi Avatar asked May 18 '15 12:05

mehdi


2 Answers

try to add the encoding property

'encoding' => 'utf-8',

heres a full copy of my working code, pls note that i pass an options array as second argument to getOutPutFromHtml()

        return new Response(
            $this->get('knp_snappy.pdf')->getOutputFromHtml($html, array(
                'orientation' => 'landscape', 
                'enable-javascript' => true, 
                'javascript-delay' => 1000, 
                'no-stop-slow-scripts' => true, 
                'no-background' => false, 
                'lowquality' => false,
                'encoding' => 'utf-8',
                'images' => true,
                'cookie' => array(),
                'dpi' => 300,
                'image-dpi' => 300,
                'enable-external-links' => true,
                'enable-internal-links' => true
            )),
            200,
            array(
                'Content-Type'          => 'application/pdf',
                'Content-Disposition'   => 'attachment; filename="report.pdf"'
            )
        );
like image 112
john Smith Avatar answered Oct 13 '22 23:10

john Smith


If you are using the generateFromHtml method, you have to use it like this, at third parameter:

$this->container->get('knp_snappy.pdf')->generateFromHtml(
    $this->container->get('templating')->render(
        'YourBundle:Template:pdfTemplate.html.twig',
        array(
            'var' => $var,
        )
    ),
    '/path/to/file.pdf',
    array(
        'encoding' => 'utf-8',
    )
);
like image 1
joan16v Avatar answered Oct 14 '22 01:10

joan16v