KnpSnappyBundle没有执行javascript

时间:2016-11-22 15:05:28

标签: javascript php jquery html symfony

我正在使用Symfony 3.1.2和KnpSnappyBundle 1.4,我按照文档中的说法(生成pdf)来跟踪:https://github.com/KnpLabs/KnpSnappyBundle

但它不起作用。生成pdf但不执行javascript ...

这是我的Symfony控制器:

/**
 * @Route("/report")
 */
public function report(Request $request)
{
    $idTown = 1;//$request->request->get("idTown"); 

    $html = $this->renderView("@AppBundle/Resources/views/report.html.twig", array
    (
        "idTown" => $idTown
    ));

    return new Response
    (
        $this->get('knp_snappy.pdf')->getOutputFromHtml($html,
                array(
                    'enable-javascript' => true,
                    'no-stop-slow-scripts' => true,
                    'javascript-delay' => 5000)
        ),
        200,
        array(
            'Content-Type'          => 'application/pdf',
            'Content-Disposition'   => 'attachment; filename="file.pdf"'
        )
    );
}

以下是HTML文件(report.html.twig):

<html>
<head>
    <script
          src="https://code.jquery.com/jquery-2.2.4.min.js"
          integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
          crossorigin="anonymous"></script>

    <script>
        $("body").html("okkkkkkkkkkkkkkkkkkkkkkk");
    </script>

    <style>
        html
        {
            background-color : red;
        }
    </style>
</head>

<body>
</body>

当我转到网址localhost/report时,我会收到一个红色页面的下载提示,其中没有文字。对于它的价值,我也尝试使用原生javascript(而不是jQuery),但它也没有用。但是你看,CSS被执行了......

请帮助,谢谢。

1 个答案:

答案 0 :(得分:0)

终于解决了。我仍然不知道为什么它不起作用,但根据我对这些html-to-pdf库的经验,总是某些东西在某些时候会出错。

我设法使用原始工具成功生成(并下载)我的pdf所有这些库都建立在wkhtmltopdf上。

这是我的代码,它可能对某些人有所帮助:

Symfony控制器:

/**
 * @Route("/report")
 */
public function report(Request $request)
{
    $idTown = 1;//$request->request->get("idTown"); 

    exec("wkhtmltopdf --disable-smart-shrinking --no-outline --margin-top 0mm --margin-bottom 0mm --margin-right 0mm --margin-left 0mm http://localhost/test --javascript-delay 3000 rapport.pdf");

    $filename = "rapport.pdf";
    header('Content-Type: application/pdf');
    header("Content-disposition: attachment;filename=$filename");
    readfile($filename);
    unlink("rapport.pdf");

    return new Response();
}

模板就是你想要的。没有问题包括资产,不需要绝对路径或所有那些狗屎等。我基本上失去了5个小时尝试不同的库,只是简单地单独使用wkhtmltopdf ...是的,你可以把JS和CSS是单独的文件。我还建议您将wkhtmltopdf放在服务器的PATH变量中,除非您想引用完整路径。

希望有一天能帮助别人。

相关问题