Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tim545/1e10d066eeec6694ea08a1322f857f00 to your computer and use it in GitHub Desktop.
Save tim545/1e10d066eeec6694ea08a1322f857f00 to your computer and use it in GitHub Desktop.
4 different ways to save a Highcharts chart as a PNG (with and without a server)
// Method 1: simply use Highcharts built-in functionality (SVG -> Highcharts server -> PNG)
// Downside: won't work in webview native apps that don't handle the form response
highcharts.exportChart({
filename: filename
});
// Method 2: Send chart config to Highcharts export server (JSON -> Highcharts server -> PNG URL)
var data = {
options: JSON.stringify(chartConfig),
filename: filename,
type: 'image/png',
async: true
};
var exportUrl = 'http://export.highcharts.com/';
$.post(exportUrl, data, function(data) {
var url = exportUrl + data;
window.open(url);
});
// Method 3: simple phantomjs server to create a PNG from the svg data (SVG -> phantomjs -> PNG)
// see https://github.com/elasticsales/flask-common/blob/master/flask_common/png.js
var svg = $chartEl.find('svg')[0];
var svgSize = svg.getBoundingClientRect();
var svgData = new XMLSerializer().serializeToString( svg );
var url = '/render_png/?' + $.param({
svg: svgData,
filename: filename
});
// Method 4: client-side-only solution (SVG -> Canvas -> PNG)
// Problem: has a security error in Safari
var canvas = document.createElement('canvas');
canvas.width = svgSize.width;
canvas.height = svgSize.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);
window.open(canvas.toDataURL('image/png'));
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment