Vanquiza Vanquiza - 1 year ago 309
Javascript Question

How do I save/export an SVG file after creating an SVG with D3.js (IE, safari and chrome)?

I currently have a website using D3 and I'd like the user to have the option to save the SVG as an SVG file. I'm using crowbar.js to do this, but it only works on chrome. Nothing happens of safari and IE gives an access denied on the

method used in crowbar.js to download the file.

var e = document.createElement('script');

if (window.location.protocol === 'https:') {
e.setAttribute('src', '');
} else {
e.setAttribute('src', '');

e.setAttribute('class', 'svg-crowbar');

How do I download an SVG file based on the SVG element on my website in safari, IE and chrome?

Answer Source

There are 5 steps. I often use this method to output inline svg.

  1. get inline svg element to output.
  2. get svg source by XMLSerializer.
  3. add name spaces of svg and xlink.
  4. construct url data scheme of svg by encodeURIComponent method.
  5. set this url to href attribute of some "a" element, and right click this link to download svg file.

//get svg element.
var svg = document.getElementById("svg");

//get svg source.
var serializer = new XMLSerializer();
var source = serializer.serializeToString(svg);

//add name spaces.
    source = source.replace(/^<svg/, '<svg xmlns=""');
    source = source.replace(/^<svg/, '<svg xmlns:xlink=""');

//add xml declaration
source = '<?xml version="1.0" standalone="no"?>\r\n' + source;

//convert svg source to URI data scheme.
var url = "data:image/svg+xml;charset=utf-8,"+encodeURIComponent(source);

//set url value to a element's href attribute.
document.getElementById("link").href = url;
//you can download svg file by right click menu.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download