Tuesday, 18 November 2014

Using javascript content (Highcharts) with mPDF PHP (plus PDO and MySQL) and phantomJS to generate server side PDFs for user download

This is something that took me a little while to figure out and put together, so I thought for my sake, and the sake of anyone else attempting to do this, I'd put up a step by step. If this is ever useful to anyone, I will be amazed, but learning is no fun if you don't try to share, I think.

Objective: 
Create server side generated PDF reports including charts and graphs typically drawn in javascript (Highcharts library)


The Problem: 
mPDF is a PHP library that will take CSS and HTML and create a PDF with it. To download it and for all information, visit their site here. mPDF does a great job accepting a wide range of CSS and HTML and creating these PDFs. But what about dynamic page content generated by javascript? mPDF does actually have some ability to render javascript, if you just want to say, add a string of text that is appended to some HTML using javascript, it can handle that kind of thing. But for a dynamic chart, it's too much. In my case my charts have a further twist in that the javascript itself is not static, but the data and series details are built using values stored in a database. So, our first problem is that javascript is typically rendered client side, in the browser, where as all this pdf geneartion is taking place server side, there is a web page emulation taking place, but as discussed not in enough fidelity to handle complex javascript. So we need something that will faithfully render javascript server side, to all us to create a file that mPDF can use when building the PDFs.

The method (overview):
We will use PHP to build a .js file which phantomjs can run, which will build a server side version of the chart as an SVG file, which mPDF can render to the PDF server side, which can then be downloaded. Details to follow.

Toolkit:

  • PHP 
  • PDO 
  • MySQL
  • Highcharts 
  • PhantomJS
  • mPDF
The method (detailed):

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home