2
votes

I want to allow my users to save my page as a PDF. I have created a print stylesheet and I can generate the PDF by using Javascript's print function. Here's my problem:

In Chrome, the browser generates a preview and shows it to the user. The user can then either save it or print it.

However, in IE and FF, print calls up a complex menu, and while it can generate a PDF by "printing" to PDFCreator, it's a complex process that many users won't understand.

What I want to do is to somehow duplicate the Chrome functionality for non-Chrome users. Options I have considered:

  • Screenshot the HTML page and render that image into a PDF with Javascript. There are libraries that do this, but I want my PDF to have the print layout.
  • Generate the PDF on the server and send it to the user's browser. This can be done, but it seems difficult to use the same HTML as the standard page.

My server is running PHP and the Zend framework. I can't use NodeJS or any headless browser to render on the server. Do I have any options?

1

1 Answers

3
votes

I've done exactly what you want to do before using a library called dompdf (https://github.com/dompdf/dompdf). Here is how I used it:

I dropped the dompdf library into the "library" folder in my ZF project. Then, in my application when I'm ready to render the page I created a new Zend_View() object and set it up with whatever view script variables it needed. Then I called the render() function and stored the rendered output into a variable I then provided to dompdf. The code looks like this:

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