How to save an image of the highcharts on the server?

Highcharts have a built-in option to export the current chart, it have the option to save the chart as PNG, JPEG, PDF or SVG.

It doesn’t have option to save the image on the server, instead of downloading in browser (clinet).

To save an image of the highcharts on the server, follow the steps:

Step 1: Create file as “highcharts.php” and save the following code:

[html]
<!– Javascript SVG parser and renderer on Canvas, used to convert SVG tag to Canvas –>
<script type="text/javascript" src="http://canvg.googlecode.com/svn/trunk/rgbcolor.js"></script>
<script type="text/javascript" src="http://canvg.googlecode.com/svn/trunk/StackBlur.js"></script>
<script type="text/javascript" src="http://canvg.googlecode.com/svn/trunk/canvg.js"></script>

<!– Hightchart Js –>
<script src="http://code.highcharts.com/highcharts.js"></script>

<!– Highchart container –>
<div id="container" style="min-width: 310px; height: 400px; margin: 0 auto"></div>

<!– canvas tag to convert SVG –>
<canvas id="canvas" style="display:none;"></canvas>

<!– Save chart as image on the server –>
<input type="button" id="save_img" value="saveImage"/>

<script type="text/javascript">
$(function () {
$(‘#container’).highcharts({
……………..
……………..
……………..
});

$("#save_img").click(function(){
var svg = document.getElementById(‘container’).children[0].innerHTML;
canvg(document.getElementById(‘canvas’),svg);
var img = canvas.toDataURL("image/png"); //img is data:image/png;base64
img = img.replace(‘data:image/png;base64,’, ”);
var data = "bin_data=" + img;
$.ajax({
type: "POST",
url: savecharts.php,
data: data,
success: function(data){
alert(data);
}
});
});
});

</script>
[/html]

Step 2: Create savecharts.php and save the following code, to save the highcharts on the server.

[php]
<?php

$data = str_replace(‘ ‘, ‘+’, $_POST[‘bin_data’]);
$data = base64_decode($data);
$fileName = date(‘ymdhis’).’.png’;
$im = imagecreatefromstring($data);

if ($im !== false) {
// Save image in the specified location
imagepng($im, $fileName);
imagedestroy($im);
echo "Saved successfully";
}
else {
echo ‘An error occurred.’;
}
[/php]

For Reference: https://code.google.com/p/canvg/

Permanent link to this article: https://blog.openshell.in/2014/08/how-to-save-an-image-of-the-highcharts-on-the-server/