Generate PDF Report with Highcharts and wkhtmltopdf

July 11th, 2018 / by api2pdf / No Comments


As a developer, you might be tasked with the challenge of generating some kind of report to PDF. The report requires graphs like line graphs, bar charts, pie charts, etc. You figure you can generate the report in HTML and then print the HTML to PDF. Great plan, let’s do it.

My favorite library for generating charts in HTML and javascript is called Highcharts.js. Highcharts is an excellent javascript library that you can use to generate all sorts of charts. In this post, we are simply using one of their demo examples – a basic line chart.

To render this report server side, we recommend using a PDF engine like wkhtmltopdf or Headless Chrome. However, simply just sending the HTML to these engines to render the PDF will yield some ugly results. There is some finagling required to make the charts look right and a couple important points.

Important Points

1 – Disable animation. By default, line charts and other charts generated by highcharts will fire off a nice animation. However, this will not work well with PDF rendering. Under the plotOptions object in the highcharts settings, set animation: false.

2 – Manipulate the width. wkhtmltopdf and Headless Chrome render PDFs sort of in the Responsive state, so assume a small width browser. You may have to continuously adjust the widths of the charts via css and the highcharts settings to ensure it looks right.

3 – Location of the legend. Same as #2, the location of the legend and how the legend appears may get mashed up in the PDF. Move it around and adjust the settings to get it looking right.

Sample Code

The following Github Gist is the basic demo line graph with adjusted settings and CSS for highcharts that make the graph look correct in the PDF. Use those settings as the baseline for the work you need to do on your own. Feel free to copy and paste this HTML into the DEMO of the home page for to see how it looks when rendered by wkhtmltopdf.

Thanks for visiting our site. If you are eager to start generating PDFs right away with just a few lines of code, grab your API key and check out our docs!

Tags: , , , ,

Comments are closed.