Skip to content

Instantly share code, notes, and snippets.

@stephanbogner
Last active October 24, 2022 12:33
Show Gist options
  • Save stephanbogner/9bbb76caa2e0ba9223b833c1377732a6 to your computer and use it in GitHub Desktop.
Save stephanbogner/9bbb76caa2e0ba9223b833c1377732a6 to your computer and use it in GitHub Desktop.
Save svg from dom as file (great when working with d3)
<a id="downloadLink" href="" download="diagram.svg">Download ↓</a>
<svg id="svg" width="120" height="120">
<rect fill="#000000" x="10" y="10" width="100" height="100"></rect>
</svg>
<script type="text/javascript">
setDownloader('downloadLink', 'svg')
function setDownloader(linkId, svgId) {
// Get svg element
var svg = document.getElementById(svgId)
// Get svg source
var serializer = new XMLSerializer()
var source = serializer.serializeToString(svg)
// Add name spaces
if (!source.match(/^<svg[^>]*?\sxmlns=(['"`])https?\:\/\/www\.w3\.org\/2000\/svg\1/)) {
source = source.replace(/^<svg/, '<svg xmlns="http://www.w3.org/2000/svg"')
}
if (!source.match(/^<svg[^>]*?\sxmlns:xlink=(['"`])http\:\/\/www\.w3\.org\/1999\/xlink\1/)) {
source = source.replace(/^<svg/, '<svg xmlns:xlink="http://www.w3.org/1999/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(linkId).href = url
}
</script>
@vHeemstra
Copy link

I assumed a generic SVG source string, that might contain other quotes. But ( new XMLSerializer() ).serializeToString( svg ) might only produce double-quoted attributes. I'm not sure, you're probably right.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment