Scenario
I was considering how I can export SVG as a file using client JavaScript. The way I found on the Internet uses XMLSerializer and create a element for download. Let’s see how it goes.
DEMO SOURCE
Solution
About
We are going to use native JavaScript only; hence, you don’t need any library but the browser compatibility of XMLSerializer must be confirmed.
It seems work on most modern browsers. :p
Create SVG Sample Element
<svg xmlns="http://www.w3.org/2000/svg" id="svg-01" width="600" height="250"> <rect fill="none" stroke="#000" stroke-width="1" x="0" y="0" width="600" height="250" /> <text class="item-title" style="font-size: 30px; font-weight: 900;" lengthAdjust="spacing" textLength="480" x="60" y="40">Export SVG using XMLSerializer</text> </svg>
Download Function
We are going to create a element for download method. The element within attributes:
- download: This is the name of download file.
- href: This is the content of download file.
function generateLink(fileName, data) { var link = document.createElement('a'); // Create a element. link.download = fileName; // Set value as the file name of download file. link.href = data; // Set value as the file content of download file. return link; }
Begin To Export!
New a XMLSerializer object and serial our SVG element to a string. Then, we have to prepend ‘data:image/svg+xml;utf8,’ for Data URIs. .click() will fire as user click.
function exportSVG(element, fileName) { var svg = element; var svgString; if (window.ActiveXObject) { svgString = svg.xml; } else { var oSerializer = new XMLSerializer(); svgString = oSerializer.serializeToString(svg); } generateLink(fileName + '.svg', 'data:image/svg+xml;utf8,' + svgString).click(); }
Click & Download
.onclick binds the function on the element.
document.getElementById('downloadBtn').onclick = function() { var element = document.getElementById('svg-01'); exportSVG(element, 'SVG-01'); }
One thought on “Export SVG file using XMLSerializer”