Search code examples
phpsymfonypdfpdf-generationwkhtmltopdf

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


Solution

  • 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"'
                )
            );