How can I save my generated svg code to a .svg file in the client machine?

2.4k views Asked by At

I used snap.svg library to generate, with javascript, a svg element in my asp.net web form page by loading other external .svg files and manipulating them in order to get the final svg element. Once the composition of the desired svg object is finish and the resulting svg element shows fine in my page, I need to save it as an .svg file in the client machine, in a user selected path. Any idea about how to do it directly? I mean, whithout sending the code to the server, generate the file in the server, and then download the file to the client machine.

2

There are 2 answers

4
Waruyama On BEST ANSWER

You can do this in two simple steps:

  1. Use new XMLSerializer().serializeToString(svg); to get a String from your SVG
  2. Use FileSaver.js to actually save the file (https://github.com/koffsyrup/FileSaver.js)

This should work in most cases (except Safari, of course).

0
Olli Niemitalo On

You can embed inline SVG code in the data URI of an img element:

<img src='data:image/svg+xml;charset=UTF-8,
<svg xmlns="http://www.w3.org/2000/svg" height="100" width="100">
    <circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" />
</svg>' />

Saving is not initiated automatically, but the user can right-click → Save image as. The SVG needs to have xmlns="http://www.w3.org/2000/svg", like in an SVG file. To embed an existing SVG element, take its outerHTML and create the img element with that HTML in the data URI, as seen above.

Caveats:

  • When saving, the default file name suggested by the browser will be something like download.svg, and I don't think you can change that.
  • Single quotes (') cannot be used in the SVG, because they are used to denote where the data URI starts and ends.
  • You cannot modify the contents of the SVG afterwards, because it is in an img tag.
  • The SVG will not use the styles of the page, but you would have that problem with the saved SVG file using any other approach, too.