On my HTML i have an SVG element. It is rendered with d3js and has stylings applied in CSS.
When i right click in my browser i can select "Save image". This actions saves the image as rendered with all the css stylings applied.
I have been searching for a good way to save the file
- Going to canvas and exporting canvas
- Filesaver with saving as SVG
- Variations on those
However when i get the file to disk the extra stylings from my css is not applied to the saved image.
Question: How can i save my SVG as rendered in the browser with css applied.
The CSS parsing is not an easy task, CSS rules are complicated...
I tried to write something for my SVG2Bitmap little script, but it is still far from being perfect...
Basically, it parses all the stylesheets in the document, and check if any of the svg's nodes match the rule (thanks to
querySelector
andElement.matches()
methods).The problem is that once appended into the svg doc, the rules may not match anymore (e.g
body>svg>rect
will fail). I still didn't find an elegant way to deal with it, also if anyone has one, please let me know.An other issue I faced is that invalid rules will make previously mentioned methods to throw an error. This shouldn't be too much of a concern, but some browsers (Chrome to not tell its name) accept some hacky rules like
[xlink\\:href]
but save it in thecssRules
as[xlink\:href]
which will fail and thus throw an error...The "save as file" part however is way easier thanks to the
XMLSerializer
object, which will let the browser create a standalone version of what it parsed, with all that is needed.To make a 100% valid svg file, you'll also need to set a Doctype at top of your document.
So let's jump in the code :
Ps : the download part of this snippet won't work in FF, you can try it in this fiddle though.
I think this should work for you:
https://stackoverflow.com/a/8694938/2308019