Skip to content Skip to sidebar Skip to footer

Is It Possible To Have A Button Start A Download Of A Dom Element?

I have an svg that is generated in a page, I am not bringing it in from an outside source. I want this svg to be downloadable for printing. Is there a way (using client side Javasc

Solution 1:

Assuming the client is using a HTML5 web browser, this can be achieved pretty easily using <a>s download attribute. You will need to simulate a click with a MouseEvent on this element if you want the behaviour to be invoked by some other means, but the node does not have to be appended to the document. I've answered a similar question about this before, but here, set the <a>s href to the svg's file location unless it is created dynamically ‒ in that case you would encode the text describing it to create a data URI.

XML text describing a SVG can be obtained from it's SVGSVGElement node using XMLSerializer.

var serializer = new XMLSerializer();
serializer.serializeToString(svg); // xml string for `svg` (your node)

Please note that any "Save As" dialogue will depend on the client's configuration.

// assuming var `svg` for your SVG nodevar a = document.createElement('a'), xml, ev;
a.download = 'my_svg.svg'; // file name
xml = (newXMLSerializer()).serializeToString(svg); // convert node to xml string
a.href = 'data:application/octet-stream;base64,' + btoa(xml); // create data uri// <a> constructed, simulate mouse click on it
ev = document.createEvent("MouseEvents");
ev.initMouseEvent("click", true, false, self, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
a.dispatchEvent(ev);

Post a Comment for "Is It Possible To Have A Button Start A Download Of A Dom Element?"