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.
How can I save my generated svg code to a .svg file in the client machine?
2.4k views Asked by MiguelGG At
2
There are 2 answers
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.
You can do this in two simple steps:
new XMLSerializer().serializeToString(svg);
to get a String from your SVGThis should work in most cases (except Safari, of course).