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

The regexes are not 100% correct, they:

  • can incorrectly match cases where there's a non-whitespace character before the xmlns attribute (for example ZZxmlns="..etc..")
  • incorrectly don't match attributes using other quote types

I made some corrected versions. See this RegEx101 example.

New regex for line #18:

^<svg[^>]*?\sxmlns=(['"`])https?\:\/\/www\.w3\.org\/2000\/svg\1

New regex for line #21:

^<svg[^>]*?\sxmlns:xlink=(['"`])http\:\/\/www\.w3\.org\/1999\/xlink\1

@stephanbogner
Copy link
Author

Thanks @vHeemstra for pointing it out and the example
I finally found time to have a look at and updated the gist 🙂
(I didn't even know ' or ` are valid in SVGs, I always thought it's just ")

@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