Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert SVG to PNG and maintain CSS integrity

I am currently using canvg() and Canvas2Image to copy my SVG to a canvas and then convert the canvas to PNG. I would like to maintain the image format and not use PDF.

How can I maintain the CSS integrity? Chart is made using NVD3.js.

downloadPhoto: function() {
  var chartArea = document.getElementsByTagName('svg')[0].parentNode;
  var svg = chartArea.innerHTML;
  var canvas = document.createElement('canvas');
  canvas.setAttribute('width', chartArea.offsetWidth);
  canvas.setAttribute('height', chartArea.offsetHeight);
  canvas.setAttribute('display', 'none');

  canvas.setAttribute(
    'style',
    'position: absolute; ' +
    'top: ' + (-chartArea.offsetHeight * 2) + 'px;' +
    'left: ' + (-chartArea.offsetWidth * 2) + 'px;');
  document.body.appendChild(canvas);
  canvg(canvas, svg);
  Canvas2Image.saveAsPNG(canvas);
  canvas.parentNode.removeChild(canvas);
}

Original SVG

SVG converted to PNG

like image 872
collenjones Avatar asked Dec 05 '13 07:12

collenjones


1 Answers

just to make @Lars Kotthoff's answer more concrete. "example of how to export a png directly from an svg" has a working example. the code snippet/gist tries to first apply all css to the svg inline and then draw the image on the canvas and export the data as png. (internally it adopted svg-crowbar code). and i apply the technique in my project and it works smoothly - a download button that can download the svg image rendered using nvd3.

like image 137
Dyno Fu Avatar answered Oct 18 '22 14:10

Dyno Fu