Nov
07
2014
by eidam

Converting svg to png with canvg

Canvg is a js library that parses svg and creates canvas. However I found out, it is also a nice way (and the only I have found so far) to convert svg to png on client. The trick is to draw a static parsed svg to hidden canvas and then take it as a url image and put inside <a> element. Then we click this element for example with jquery click().

This should be done with this code

html :

js:

 

This looks easy and nice. But the real problem came when I realized there is no possibility to include external css styles. Solution for this problem was strongly inspired by this discussion https://code.google.com/p/canvg/issues/detail?id=143 . As we are not able to include a real css files, we have to use CDATA construct inside svg structure to enabling us towrite various code. So here we could append  a <style> tag with all our implemented css rules. This rules are in my case obtained with iteration over document.styleSheets, but also ajax or another solution could be used. My iteration looks almost exactly like the one from that discussion I mentioned above. Assuming I have all my rules for this svg in one separated css file (svg.css) I use this code:

Then I appended this style string wrapped to <style> element and “![CDATA[]]” to svg container

 

And here is a “working” example on codepen (codepen doesnt support downloading files):

See the Pen Donwload svg as png by Eidam (@eidam61) on CodePen.