使用Knp Snappy生成pdf文件时出现错误字符

时间:2015-05-18 12:27:48

标签: php symfony pdf pdf-generation wkhtmltopdf

我正在使用Symfony2。使用以下代码生成pdf文件时:

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

我收到此内容(法语字符显示为坏字符): enter image description here

2 个答案:

答案 0 :(得分:14)

尝试添加encoding属性

'encoding' => 'utf-8',

这是我工作代码的完整副本,请注意我将一个options数组作为第二个参数传递给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"'
            )
        );

答案 1 :(得分:1)

如果您使用generateFromHtml方法,则必须在第三个参数中使用它:

$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',
    )
);