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.
Asked
Active
Viewed 2,354 times
2 Answers
4
You can do this in two simple steps:
- Use
new XMLSerializer().serializeToString(svg);
to get a String from your SVG - Use FileSaver.js to actually save the file (https://github.com/koffsyrup/FileSaver.js)
This should work in most cases (except Safari, of course).

Waruyama
- 3,267
- 1
- 32
- 42
-
1It is very difficult / impossible to save files locally with Javascript on Safari. You can find a huge discussion thread on this subject at https://github.com/eligrey/FileSaver.js/issues/12 – Waruyama Jun 15 '15 at 20:51
-
1ok, actually just a link with the dataUrl and a notice to right-click, "save the file as..." will do the trick for browsers which don't support `download` attribute. – Kaiido Jun 16 '15 at 00:02
-
I have tried it, but what I get is "Uncaught TypeError: Failed to execute 'serializeToString' on 'XMLSerializer': parameter 1 is not of type 'Node'." – Anastasios Oikonomidis Sep 19 '21 at 08:22
-
1@AnastasiosOikonomidis Then your svg parameter is not an SVG node. Try "console.log(typeof svg)) before you call the XMLSerializer to see what you are actually passing to the function. – Waruyama Sep 19 '21 at 13:51
0
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.

Olli Niemitalo
- 153
- 12