Blog
Export AnyChart graph to PDF with wkhtmltopdf
Intro
We previously made a post on how to export a HighChart graph to PDF using the wkhtmltopdf endpoint. This time we are going to cover AnyChart, which is arguably better than HighCarts in many areas. In this post we are going to cover printing an AnyChart graph to PDF with wkhtmltopdf.
Sample Code
The following sample code is taken from the AnyChart website demo for a basic Area chart. We are going to use this as the baseline for printing to PDF.
<html> | |
<head> | |
<script src="https://cdn.anychart.com/releases/8.3.0/js/anychart-base.min.js"></script> | |
<style> | |
#container { | |
min-width: 800px; | |
max-width: 800px; | |
height: 400px; | |
margin: 0 auto | |
} | |
</style> | |
</head> | |
<body> | |
<div id="container"></div> | |
<script> | |
// create data | |
var data = [ | |
["January", 10000], | |
["February", 12000], | |
["March", 18000], | |
["April", 11000], | |
["May", 9000] | |
]; | |
// create a chart | |
chart = anychart.area(); | |
// create an area series and set the data | |
var series = chart.area(data); | |
// set the container id | |
chart.container("container"); | |
// initiate drawing the chart | |
chart.draw(); | |
</script> | |
</body> | |
</html> |
Export to PDF
Using the wkhtmltopdf endpoint from the Api2Pdf documentation, you have two options.
- Convert from URL – You can generate a web page that displays the HTML as you desire and then use the Convert Webpage to PDF. Api2Pdf will visit that URL and convert it to PDF accordingly. Another approach is to save the HTML to a .html file type and upload that to a file server like Amazon S3. Then pass the URL to the .html file the same way as you would any URL to generate the PDF.
- Convert HTML to PDF straight away by using the POST endpoint to send the raw HTML directly.
Important Point
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.