Search code examples
svgclient-sidefilesaver.jsjsxgraph

How to save client side rendered svg graphic as svg file?


There are several javascript libraries which render svg images on the client side.

Example

JSXGraph

Screenshot

enter image description here

It's easy to make a screenshot of the svg image but is it possible to download the image as a svg file from the client side?

A possible workaround

On the server side it is possible, so maybe by downloading the page and modifying the source code (add var svg = new XMLSerializer().serializeToString(board.renderer.svgRoot); and FileSaverJS) it can be done?! Isn't there an easier solution?


Solution

  • Indeed, new XMLSerializer().serializeToString(board.renderer.svgRoot); returns the SVG code. Alternatively, JSXGraph offers the method board.renderer.dumpToDataURI(ignoreTexts) which returns a base64 encoded data URI of the SVG code. If called with the parameter ignoreTexts==false, those JSXGraph elements which are displayed as HTML elements, like some texts, will be enclosed in a foreignObject tag in the SVG.

    So, if you want to use board.renderer.dumpToDataURI to get SVG source code, you have to base64 decode it like this:

    atob(board.renderer.dumpToDataURI(false).split(',')[1]);
    

    See https://jsfiddle.net/s9ch1e73/1/ for a working example.

    If you just want to copy the SVG code from a working example, you can paste the above code into the JavaScript console of the browser and copy the output.