This is just a combination of solutions founded from Stackoverflow
Last active
May 13, 2021 21:23
-
-
Save Karobwe/54de7f01dd7561ad872c3d1ce2243741 to your computer and use it in GitHub Desktop.
Save SVG from a web page
This file contains hidden or 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
function saveSVGToDisk(elementId) { | |
let svg = document.getElementById(elementId); | |
//get svg source. | |
let serializer = new XMLSerializer(); | |
let source = serializer.serializeToString(svg); | |
//add name spaces. | |
if(!source.match(/^<svg[^>]+xmlns="http\:\/\/www\.w3\.org\/2000\/svg"/)){ | |
source = source.replace(/^<svg/, '<svg xmlns="http://www.w3.org/2000/svg"'); | |
} | |
if(!source.match(/^<svg[^>]+"http\:\/\/www\.w3\.org\/1999\/xlink"/)){ | |
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. | |
let url = "data:image/svg+xml;charset=utf-8,"+encodeURIComponent(source); | |
// Save file to disk | |
var link = document.createElement("a"); | |
document.body.appendChild(link); | |
link.setAttribute("type", "hidden"); | |
link.href = url; | |
link.download = "your-file"; | |
link.click(); | |
document.body.removeChild(link); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment