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);
iframe
whose src
is the submit url. Give it an id
.input
. Set the value
of this input
to the serialized SVG content.id
given to the iframe
, and whose action
is the submit url. Put the input
inside the form
.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/png
Content-Disposition:attachment; filename=mypng.png
The 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). data
is the serialized SVG:
function ajaxFileDownload(url, data) {
var iframeId = "uniqueIFrameId"; // Change this to fit your code
var iframe = $("#" + iframeId);
// Remove old iframe if there
if(iframe) {
iframe.remove();
}
// Create new iframe
iframe = $('<iframe src=""' + url + '"" name="' + iframeId + '" id="' + iframeId + '"></iframe>')
.appendTo(document.body)
.hide();
// Create input
var input = '<input type="hidden" name="data" value="' + encodeURIComponent(data) + '" />';
// Create form to send request
$('<form action="' + url + '" method="' + 'POST' + '" target="' + iframeId + '">' + input + '</form>')
.appendTo(document.body)
.submit()
.remove();
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With