Convert SVG to PNG and maintain CSS integrity

I am currently using canvg () and Canvas2Image to copy SVG to canvas and then convert the canvas to PNG. I would like to keep the image format and not use PDF.

How can I maintain CSS integrity? The diagram is made using NVD3.js.

downloadPhoto: function() { var chartArea = document.getElementsByTagName('svg')[0].parentNode; var svg = chartArea.innerHTML; var canvas = document.createElement('canvas'); canvas.setAttribute('width', chartArea.offsetWidth); canvas.setAttribute('height', chartArea.offsetHeight); canvas.setAttribute('display', 'none'); canvas.setAttribute( 'style', 'position: absolute; ' + 'top: ' + (-chartArea.offsetHeight * 2) + 'px;' + 'left: ' + (-chartArea.offsetWidth * 2) + 'px;'); document.body.appendChild(canvas); canvg(canvas, svg); Canvas2Image.saveAsPNG(canvas); canvas.parentNode.removeChild(canvas); } 

Original SVG

SVG converted to PNG

+8
png svg librsvg
source share
3 answers

Style definitions for svg elements defined in style sheets do not apply to the generated canvas. This can be fixed by adding style definitions to svg elements before calling canvg.

Inspired by this article , I created this:

 function generateStyleDefs(svgDomElement) { var styleDefs = ""; var sheets = document.styleSheets; for (var i = 0; i < sheets.length; i++) { var rules = sheets[i].cssRules; for (var j = 0; j < rules.length; j++) { var rule = rules[j]; if (rule.style) { var selectorText = rule.selectorText; var elems = svgDomElement.querySelectorAll(selectorText); if (elems.length) { styleDefs += selectorText + " { " + rule.style.cssText + " }\n"; } } } } var s = document.createElement('style'); s.setAttribute('type', 'text/css'); s.innerHTML = "<![CDATA[\n" + styleDefs + "\n]]>"; //somehow cdata section doesn't always work; you could use this instead: //s.innerHTML = styleDefs; var defs = document.createElement('defs'); defs.appendChild(s); svgDomElement.insertBefore(defs, svgDomElement.firstChild); } // generate style definitions on the svg element(s) generateStyleDefs(document.getElementById('svgElementId')); 
+4
source share

The main thing is that all style rules should be part of SVG, and not in external style files. Therefore, you will need to go through all the CSS for NVD3 and set all these attributes in the code. Anything set through an external stylesheet will be ignored.

+2
source share

just to make @Lars Kotthoff more specific. " an example of how to export png directly from svg " has a working example. The / gist code snippet first tries to apply all the css to svg inline, and then draw an image on the canvas and export the data as png. (internally, he accepted the svg-crowbar code). and I apply the technique in my project, and it works smoothly - a download button that can load the svg image displayed with nvd3 .

0
source share

All Articles