Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Downloading a dynamically generated SVG file from the browser

Tags:

html

svg

If I create an image using HTML SVG element, can I then offer this as an SVG file download to the user. For example I may want to load an SVG image, apply some basic transformations to it, add some text, then let the user download the result as a vector image.

Is that possible? I have been doing something similar with Canvas but have been struggling creating a vector image. I wasn't aware that SVG elements were so versatile when I cam across them this morning but if I can do the above it would be great.

like image 869
jcvandan Avatar asked Aug 25 '13 11:08

jcvandan


1 Answers

Simple solution using a data URI:

var svg_root = document.getElementById('your_svg_root_element_here');
var svg_source = svg_root.outerHTML;
var svg_data_uri = 'data:image/svg+xml;base64,' + btoa(svg_source);
var link = document.getElementById('anchor_element');
link.setAttribute('href', svg_data_uri);

Although it worked, when clicking on the link, the browser stalled for a few seconds.

This seems to be the simplest solution and should be compatible with all modern browsers. However, it has some noticeable overhead. If someone else knows a different solution (maybe using blobs or something similar), please add here as another answer!

like image 119
Denilson Sá Maia Avatar answered Nov 14 '22 22:11

Denilson Sá Maia