X
    Categories: PHP

How to save highcharts graph to image on server?

How to save highcharts graph to image on server?

In this tutorial we are going to see about how to store Highcharts into server using php.

Highcharts will provide more powerfull and easy chart structure comparing with other charts.

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).

Here I have explained how to store the graph in server using php.

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:

<!-- 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>

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

<?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.';
}

If you like this article don’t forget to share and comment!.

Thanks!.

Marimuthu :