简体   繁体   中英

SVG to PNG with Embedded Style Sheet

I'm interested in creating a PNG from SVG. I followed the code given in:

https://developer.mozilla.org/en-US/docs/HTML/Canvas/Drawing_DOM_objects_into_a_canvas

But the image does not come out right due to styling from CSS. I made a local CSS file and do an import into the SVG, as described in:

How to apply a style to an embedded SVG?

But it does not appear to be using the style sheet. Any ideas why I would have this error?

Thanks.

Have a look at PhantomJS - You need to install it then either write your own script or run something along these lines:

phantomjs rasterize.js http://ariya.github.com/svg/tiger.svg tiger.png

You can also save to PDF, set Zoom setting, etc.

You could use html2canvas to generate a canvas from any dom element (including svg elements).

However, style definitions for svg elements defined in stylesheets are not applied to the generated canvas. This can be patched by adding style definitions to the svg elements before calling html2canvas.

Inspired on this article , I've 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'));

// after generating the style defintions, call html2canvas
html2canvas(document.getElementById('idOfElement')).then(function(canvas) {
  document.body.appendChild(canvas);
});

The example at

"How to apply a style to an embedded SVG?" as you mentioned should work. You need to define youObjectElement in this line of code when you test it.

var svgDoc = yourObjectElement.contentDocument;

try again.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM