Problems with exportation to image with highcharts ? Try these methods !

3 Ways to export highcharts charts to image with javascript (client side solution)

A lot of problems while exporting highcharts charts to image locally can appear on the runtime. Bad resolution, the image is generated with a little piece of the chart, a custom chart doesn't get exported as expected .. and a lot more.

Include the following code in your document (save as a file or include it with a script tag)  and choose the method that best suits your needs.

Note : The given code assumes that you already linked in your document jQuery (optional, you can change the selectors with pure javascript selectors) and Highcharts_export.js (Required for 2 of the given methods) which can be downloaded  here. This code aims to help you with the generation of an image with highchart or native svg to image, that means you can modify or share the code as you like.

/**
  * Highcharts exportation functions
  * @author Our Code World
  */
 (function(window){
    
    function ExportInitializator(){
        var exp = {};
        
 
        var EXPORT_WIDTH = 1000;  // Exportation width
        
		
		/**
		 * This method requires the highcharts_export.js file 
		 */
        exp.highchartsSVGtoImage = function(chart,callback) {
            var svg = chart.highcharts().getSVG();
            var canvas = document.createElement('canvas');
            canvas.width = chart.width();
            canvas.height = chart.height();
            var ctx = canvas.getContext('2d');

            var img = document.createElement('img');

            img.onload = function() {
                ctx.drawImage(img, 0, 0);
                callback(canvas.toDataURL('image/png'));
            };

            img.setAttribute('src', 'data:image/svg+xml;base64,' + btoa(unescape(encodeURIComponent(svg))));
        };
        
        /**
		 * This method requires the highcharts_export.js file 
		 */
        exp.highchartsCustomSVGtoImage = function(chart,callback){
            if(!chart){
                console.error("No chart given ");
            }
            var render_width = EXPORT_WIDTH;
            var render_height = render_width * chart.chartHeight / chart.chartWidth;

            var svg = chart.getSVG({
                exporting: {
                    sourceWidth: chart.chartWidth,
                    sourceHeight: chart.chartHeight
                }
            });
            
 
            
            var canvas = document.createElement('canvas');
            canvas.height = render_height;
            canvas.width = render_width;
            var image = new Image();
            image.src = 'data:image/svg+xml;base64,' + btoa(unescape(encodeURIComponent(svg)));
            console.log(image);
            image.addEventListener('load', function() {
                console.log(chart);
                canvas.getContext('2d').drawImage(this, 0, 0, render_width, render_height);
                callback(canvas.toDataURL('image/png'));
            }, false);

            image.src = 'data:image/svg+xml;base64,' + window.btoa(svg);
        };
         
		
		/**
		 * This method requires the highcharts_export.js file 
		 */
        exp.nativeSVGtoImage = function(DOMObject,callback,format){
            if(!DOMObject.nodeName){
                throw new error("Se requiere un objeto DOM de tipo SVG. Obtener con document.getElementById o un selector de jQuery $(contenedor).find('svg')[0]");
            }
                    
            var svgData = new XMLSerializer().serializeToString(DOMObject);
            var canvas = document.createElement("canvas");
            canvas.width = $(DOMObject).width();
            canvas.height = $(DOMObject).height();
            var ctx = canvas.getContext( "2d" );
            var img = document.createElement("img");
            img.setAttribute( "src", "data:image/svg+xml;base64," + btoa(unescape(encodeURIComponent(svgData))) );
            img.onload = function() {
                ctx.drawImage( img, 0, 0 );
                
                if(format === "jpeg" || format === "jpg"){
                    callback(canvas.toDataURL("image/jpeg"));
                }else{
                    callback(canvas.toDataURL("image/png"));
                }
            }; 
            return true;
        };
        
        return exp;
    }
    
    if(typeof(highchartsExport) === 'undefined'){
        window.highchartsExport = new ExportInitializator();
    }
})(window);

highchartsSVGtoImage

This method expects a jQuery selector of highcharts (or a variable that contains a highchart) and calls the method getSVG from it. A image is created and it's source will be the previous svg result, then a canvas is created and the previous image is drawn on it and we can generate a base64 image from the canvas. (the dimensions of this image are the same as the svg container )

Note : This functions is not synchronous, for this reason the 2nd parameters expects to be a function (which receives as first parameter the base64 uri).

Usage

highchartsExport.highchartsSVGtoImage($("#myChartContainer"),function(uri){
   window.open(uri);
});

 

highchartsCustomSVGtoImage

This method expects a jQuery selector of highcharts calling the function and then calls the method getSVG from it. A image is created and it's source will be the previous svg result, then a canvas is created and the previous image is drawn on it and we can generate a base64 image from the canvas.(the width of this image will be the result from the custom property "EXPORT_WIDTH" declared in the top of the script and the following operation will be executed : render_width * chart.chartHeight / chart.chartWidth)

Note : This functions is not synchronous, for this reason the 2nd parameters expects to be a function (which receives as first parameter the base64 uri).

Usage

highchartsExport.highchartsCustomSVGtoImage($("#myChartContainer").highcharts(),function(uri){
   window.open(uri);
});

 

nativeSVGtoImage

This method expects a native SVG dom object. A image is created  and it's source will be the previous svg result (which will be interpreted by the XMLSerializer), then a canvas is created and the previous image is drawn on it and we can generate a base64 image from the canvas.

Note : This functions is not synchronous, for this reason the 2nd parameters expects to be a function (which receives as first parameter the base64 uri).

Usage

highchartsExport.nativeSVGtoImage($("#myChartContainer").find("svg")[0],function(uri){
   window.open(uri);
},'png');

Do you have more methods to export highcharts locally ? Share it with us in the comment box down here.


Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Sponsors