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" >
 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:

View Comments

  • Hi,, thanks for your instructions.
    In my case it just renders a black image.
    Can someone tell where the fault can be?

    The js code:

    // get the svg data from the chart holder
    var svg = document.getElementById(DOMId).children[0].innerHTML;

    // create a target canvas element
    var target = document.getElementById('target1');

    // bind svg data to the target canvas element
    canvg(target, svg);

    // convert svg data to an image/png;base64 format
    var img = target.toDataURL('image/png');
    img = img.replace('data:image/png;base64,', '');

    // post data to application so the file can be saved
    var bindata = "bindata=" + img;
    $.ajax({
    type: 'POST',
    url: 'path-to-handler',
    data: bindata,
    success: function(data) { chartExported(data); }
    });

    The php code:

    $image = imagecreatefromstring(base64_decode(
    str_replace(' ', '+', $request->getPostParameter('bindata')
    )));

    if ($image !== false) {
    imagepng($image, $filename);
    imagedestroy($image);
    return $this->renderText('success');
    }
    else {
    return $this->renderText('error');
    }

  • I've chosen a new strategy. Because I want to
    use the images in a PDF document, I can use the SVG. So I grab the SVG
    data with the Highcharts.getSVG() method for each chart and send that
    with an Ajax post to my server side handler. Since SVG is plain XML, itś
    easy to save that to a file, which I can use later on.

  • Hi, Am getting error like below in ajax response
    Warning: imagecreatefromstring(): Empty string or invalid image

    • Hi Siva,

      Please check in your ajax,

      var data = "bin_data=" + img;

      I guess, There is no value for "img" variable, Just give alert for img variable before pass it to PHP file in ajax.

      It should retrun image in base64 format.

      Thanks!.

      • i have one more question for u in your code u can call ajax after click event but in my case when graph is create after that his image is create without any click event... is there any way...??

          • Here is my code .. after ajax call img is created but in image graph is not showing ....u can try this

            Highcharts.chart('container', {
            chart: {
            type: 'column'
            },
            title: {
            text: 'Graph chart for test Project Report '
            },
            xAxis: {
            categories: ['Apples', 'Oranges', 'Pears', 'Grapes', 'Bananas']
            },
            yAxis: {
            min: 0,
            title: {
            text: 'Total fruit consumption'
            }
            },
            tooltip: {
            pointFormat: '{series.name}: {point.y} ({point.percentage:.0f}%)',
            shared: true
            },

            plotOptions: {
            column: {
            stacking: 'percent'
            }
            },
            series: [{

            name: 'Priyank',
            data: [5, 3, 4, 7, 2]
            }, {
            name: 'Jane',
            data: [2, 2, 3, 2, 1]
            }, {
            name: 'Joe',
            data: [3, 4, 4, 2, 5]
            }],
            events: {
            load: function(event) {
            myFunction();
            }
            }

            },function(chart){

            //$("#save_img").trigger("click");
            myFunction();
            }
            );

            //$("#save_img").click(function(){
            function myFunction(){

            var a = $("#container").val();
            console.log(a+"--");

            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 : '/test/ajax',
            data: data,
            success: function(data){

            }
            });
            }
            //});

          • chart: {
            type: 'column',
            events: {
            load: function(event) {
            setTimeout(function(){ alert("Hello"); }, 3000);
            }
            }
            }

            After chart Load I have called the alert with timeout function. Instead of alert you can call your functions.