Home > Back-end >  Download a svg file by clicking a link
Download a svg file by clicking a link

Time:04-12

I have an svg that represents a force directed graph. I wish to download this svg on the click of a link and save it as a svg file. After trying several solutions from other similar posts, I have come up with this function that will be called uppon click of the button:

<a id="svglink" href=""  @click="saveSvg2" download="testSvg.svg" >DOWNLOAD</a>
saveSvg2(){
    // https://askcodez.com/comment-puis-je-enregistrer-exporter-un-fichier-svg-apres-la-creation-dun-svg-avec-d3-js-ie-safari-et-chrome.html
    //get svg element.
    var svg = document.getElementById("graph").child; // this.exportableMap

    //get svg source.
    var serializer = new XMLSerializer();
    var 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.
    var url = "data:image/svg xml;charset=utf-8," encodeURIComponent(source);
  
    //set url value to a element's href attribute.
    document.getElementById("svglink").href = url;
    
    },

It works if I use a button and right click the button and save it from there but I want it to download on left click and with a predifined file name. Ideally by left clicking a link but a button can work too if easier to implement How can I accomplish this ?

CodePudding user response:

Make sure that you are running this from a web server. I use the blob scheme but I guess it's the same for the data scheme. The example below cannot run in a ST snippet, therefore I made a codepen example. When you inspect the link after clicking it the first time you can see that the href has the value blob:https://cdpn.io/[some id]. The URL is a sign that it should work. If the page does not run from a server the value of href will be something like blob:null/[some id].

I know I skipped some of your code, but this is a minimal example of how you can use Blob to convert markup like the SVG string into a data URL.

document.links.svglink.addEventListener('click', e => {
  let svg = document.querySelector('svg').outerHTML;
  let blob = new Blob([svg], {type : 'image/svg xml'});
  e.target.href = URL.createObjectURL(blob);
});
<svg viewBox="0 0 100 100" width="100" xmlns="http://www.w3.org/2000/svg">
  <rect width="100" height="100" fill="orange" />
</svg>

<a name="svglink" href="javascript:void(0)" download="hello.svg">DOWNLOAD</a>
  • Related