Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save an svg generated by raphael

Tags:

svg

raphael

Is there a way to save the SVG generated by raphael as an svg file. Note it only need to work in chrome.

like image 414
Andreas Köberle Avatar asked Apr 12 '12 09:04

Andreas Köberle


People also ask

How to save SVG files?

You can use the Save As feature to save to the SVG format directly. Choose File > Save As from the Menu Bar. You can create a file and then choose File > Save As to save the file. In the save window, change the Format to SVG (svg) and then click Save.

What program opens SVG files?

Adobe Illustrator, known for creating vector-based artwork, natively supports both loading and saving files in SVG format. Also, Inkscape and GIMP are two free programs that can save artwork in SVG format.


3 Answers

I came up with a solution using Raphael.Export, which gives me an valid svg/xml String (something that I couldn't get from the simply from the innerHTML of the DOM object that holds the svg) and Blobbuilder to create a url for a link which will I fire a click event at the end to save the file.

svgString = @paper.toSVG();
a = document.createElement('a');
a.download = 'mySvg.svg';
a.type = 'image/svg+xml';
bb = new(window.BlobBuilder || WebKitBlobBuilder);
bb.append(svgString);
blob = bb.getBlob('image/svg+xml');
a.href = (window.URL || webkitURL).createObjectURL(blob);
a.click();
like image 87
Andreas Köberle Avatar answered Nov 06 '22 00:11

Andreas Köberle


As stef commented, the BlobBuilder API is deprecated. Instead, use the Blob API.

Building on Andreas' answer, here is how I quickly got it to work:

svgString = r.toSVG();
a = document.createElement('a');
a.download = 'mySvg.svg';
a.type = 'image/svg+xml';
blob = new Blob([svgString], {"type": "image/svg+xml"});
a.href = (window.URL || webkitURL).createObjectURL(blob);
a.click();
like image 45
Neema Avatar answered Nov 06 '22 01:11

Neema


If you don't want to use the Rapahel.Export, you can directly get the svg from the dom, like that:

var svgString = document.getElementById('holder').innerHTML;
a = document.createElement('a');
a.download = 'mySvg.svg';
a.type = 'image/svg+xml';
blob = new Blob([svgString], {"type": "image/svg+xml"});
a.href = (window.URL || webkitURL).createObjectURL(blob);
a.click();

"holder" is the id of the div where is loaded Raphael : r = Raphael("holder"); Note that I think it won't work on old browser that doesn't handle svg

like image 28
Remy Mellet Avatar answered Nov 06 '22 01:11

Remy Mellet