'How to declare XML namespace in Javascript for xlink:href and download the SVG file
I have a D3JS tree that I want to download as SVG. I am successful in downloading and rendering the SVG file if I use the following code and parse it to replace the first <g> and last </g> with <svg></svg> tags:
$('#download-SVG').click(function() {
var dl = document.createElement('a');
document.body.appendChild(dl); // This line makes it work in Firefox.
dl.setAttribute("href", svgDataURL(svg.node()));
dl.setAttribute("download", "test.svg");
dl.click();
});
I replaced the createElement and setAttribute with createElementNS and setAttributeNS as in the code below:
$('#download-SVG').click(function() {
var dl = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
dl.setAttribute('viewBox', '-2500 -420 6000 10000');
dl.setAttribute("width", "100%");
dl.setAttribute("height", "100%");
dl.setAttributeNS('http://www.w3.org/1999/xlink', 'href', svgDataURL(svg.node()));
document.body.appendChild(dl); // This line makes it work in Firefox.
dl.setAttribute("download", "test.svg");
dl.click();
});
function svgDataURL(svg) {
var svgAsXML = (new XMLSerializer).serializeToString(svg);
var dataURL = "data:image/svg+xml," + encodeURIComponent(svgAsXML);
return dataURL;
}
The SVG tags are inserted correctly, however, I get the following error if I try to open the file in Chrome:
error on line 1 at column 45779: Namespace prefix xlink for href on svg is not defined
which is due to xmlns not being declared. I have assuemed that setArrtibuteNS would do that!
A snippet from the SVG file (from Chrome Inspect):
<svg viewBox="-2500 -420 6000 10000" width="100%" height="100%" xlink:href="data:image/svg+xml,%3Cg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20transform%3D%22translate(700%2C25)scale(.7%2C.7)%22%3E%3Cpath%20class%3D%22link%22%20stroke%3D%22%23ccc% …… 3C%2Fg%3E" download="test.svg"></svg>
Also I get the error
custom.js:166 Uncaught TypeError: dl.click is not a function
which works in the original code.
Any explanation of both these would be appreciated.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
