Last active
October 24, 2022 12:33
-
-
Save stephanbogner/9bbb76caa2e0ba9223b833c1377732a6 to your computer and use it in GitHub Desktop.
Save svg from dom as file (great when working with d3)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
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 "
)
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
The regexes are not 100% correct, they:
xmlns
attribute (for exampleZZxmlns="..etc.."
)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