使用打印布局将 HTML 页保存为 PDF

Save HTML page to PDF with print layout

我想让我的用户将我的页面另存为 PDF。我创建了一个打印样式表,我可以使用 Javascript 的 print 函数生成 PDF。这是我的问题:

Chrome中,浏览器生成预览并显示给用户。然后用户可以保存或打印它。

然而,在 IE 和 FF 中,print 调出一个复杂的菜单,虽然它 可以 通过 "printing" 生成 PDF 到 PDFCreator,它是许多用户无法理解的复杂过程。

我想做的是以某种方式为非Chrome 用户复制Chrome 功能。我考虑过的选项:

我的服务器是运行PHP和Zend框架。我不能使用 NodeJS 或任何无头浏览器在服务器上呈现。我有什么选择吗?

在使用名为 dompdf (https://github.com/dompdf/dompdf) 的库之前,我已经完成了您想做的事情。这是我的使用方法:

我将 dompdf 库放入 ZF 项目的 "library" 文件夹中。然后,在我的应用程序中,当我准备好呈现页面时,我创建了一个新的 Zend_View() 对象并使用它需要的任何视图脚本变量对其进行设置。然后我调用了 render() 函数并将渲染的输出存储到一个变量中,然后我提供给 dompdf。代码如下所示:

        $html = new Zend_View();
        $html->setScriptPath(APPLICATION_PATH . '/views/scripts/action_name/');
        $html->assign($data); //$data contains the view variables I wanted to populate.
        $bodyText = $html->render('pdf_template.phtml');
        require_once(APPLICATION_PATH."/../library/dompdf/dompdf_config.inc.php");
        $dompdf = new DOMPDF();
        $dompdf->load_html($bodyText);
        // Now you can save the rendered pdf to a file or stream to the browser:
        $dompdf->stream("sample.pdf");

        // Save to file:
        $dompdf->render();
        $pdf = $dompdf->output();
        file_put_contents($filename, $pdf);