I am new to SVG and not an advanced user of JavaScript. I have a webpage with svg content dynamically rendered by javascript. In Internet Explorer when I right click on the svg content, I get option “Save Picture As” and I am able to save the content as png or svg.
How do I programatically do it by having a button and allow user to save the content in png on to their machine.
From my research there is no way to do this without sending the svg content to your server and having it return the data to save as a file download.
However, even this is tricky to achieve with a single AJAX-style request and the solution is amazingly convoluted. Others have linked to other posts that explain this, but I already went through the same answers and none of them explain it very well.
Here are the steps that worked for me:
Use JavaScript to serialize the SVG content.
var svgString = new XMLSerializer().serializeToString(svgElement);iframewhosesrcis the submit url. Give it anid.input. Set thevalueof thisinputto the serialized SVG content.idgiven to theiframe, and whoseactionis the submit url. Put theinputinside theform.form.On your server, use whatever tools are available (I don’t use .NET so you’re on your own here…) to convert the SVG document to a PNG. Send the PNG content back to the client, making sure to use the headers:
Content-Type:image/pngContent-Disposition:attachment; filename=mypng.pngThe browser should initiate a file download on the returned content, although this is browser-dependent and I’m not certain but some browsers may choose to open images in a new tab instead of opening a file download dialog.
Here is an (imperfect) function that will do the AJAX work (uses JQuery but you should get the idea).
datais the serialized SVG:Note that this URL-encodes the SVG content, so you will have to decode it on your server before converting to PNG.
Also note that if you have defined styles for your SVG in an external stylesheet, they will not be serialized. I decided to put all styles inline on the elements as presentation attributes for this reason.
I hope this helps.