Skip to content

Instantly share code, notes, and snippets.

@philfreo
Created August 22, 2014 21:38
Show Gist options
  • Star 46 You must be signed in to star a gist
  • Fork 8 You must be signed in to fork a gist
  • Save philfreo/0a4d899de4257e08a000 to your computer and use it in GitHub Desktop.
Save philfreo/0a4d899de4257e08a000 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'));
};
@markzolotoy
Copy link

Any way to generate an image in .NET without using PhantomJS or sending it to the Highcharts export server?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment