Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save <svg> HTML5 to PNG or image

Tags:

html

export

svg

I have got charts generated with D3 Javascript library and i need to save these to file PNG or SVG.

Is there some library that makes the job?

I found this https://github.com/sampumon/SVG.toDataURL but is not working on my html5, in firefox console i got this error:

NS_ERROR_NOT_AVAILABLE: Component is not available [Interrompi per questo errore]

ctx.drawImage(img, 0, 0);

like image 727
Salvatore Dibenedetto Avatar asked Jan 31 '13 17:01

Salvatore Dibenedetto


Video Answer


2 Answers

Example from developer.mozilla.org demonstrating how to export svg to png using canvas element.

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');

var data = '<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200">' +
           '<foreignObject width="100%" height="100%">' +
           '<div xmlns="http://www.w3.org/1999/xhtml" style="font-size:40px">' +
             '<em>I</em> like ' + 
             '<span style="color:white; text-shadow:0 0 2px blue;">' +
             'cheese</span>' +
           '</div>' +
           '</foreignObject>' +
           '</svg>';

var DOMURL = window.URL || window.webkitURL || window;

var img = new Image();
var svg = new Blob([data], {type: 'image/svg+xml'});
var url = DOMURL.createObjectURL(svg);

img.onload = function () {
  ctx.drawImage(img, 0, 0);
  DOMURL.revokeObjectURL(url);
  var png_img = canvas.toDataURL("image/png");
}

img.src = url;
like image 147
Rafał R Avatar answered Oct 15 '22 09:10

Rafał R


Server-side script method

Here is a simple method to save svg elements to png(though it uses server-side scripting, which may be different from what you'd expect): Checkout this page.

As is documented by the author, the client extract the svg element (using XMLSerializer.serializeToString)and send it to server; the server convert it to png and send it back to the client. The server can use any program that is convenient(rsvg-convert in this case).

Canvg library

You can use this library to do this on client side (check it out!):

canvg is a SVG parser and renderer. It takes a URL to a SVG file or the text of an SVG file, parses it in JavaScript, and renders the result on a Canvas element

Use it like this:

//load a svg snippet in the canvas with id = 'drawingArea'
canvg(document.getElementById('drawingArea'), '<svg>... </svg>')

Then you can use the toDataURL method: document.getElementById('drawingArea').toDataURL('image/png');

like image 33
wzhd Avatar answered Oct 15 '22 08:10

wzhd