How to Include CSS style when converting svg to png

Question 1 (first half): what’s the real reason (is the GPU acceleration related in anyway?)

No, GPU acceleration has nothing to do with it.
The broadest reason is privacy.

To draw your svg with drawImage you have to load your svg as an external document inside an <img> tag. SVG can be quite a complex image format for resources loading (it can literally require any kind of resource that could be required by any HTML document). Thus, it has been stated in specs that the same security as the one for <iframe> elements or <object> or similar ones should apply to <img> content and even stricter :

<img> content can not require any external resources, nor access to the main document.

Question 1 (second half): and the solution for this issue

You pointed to some SO questions already answering it, you could also just include all the stylesheets from the main document inside a <style> tag inside your parsed svg Node, before you do create the Blob from it. dumb implementation here

Question 2 : “how i still overcome this issue when using a custom font with Fontface”

For external resources, you have to encode it as dataURI, and include it in your svg node before you create the Blob. For font in particular, you’d set a font-face property in a <style> element.

So at the end, your svg would have something like

<defs>
  <style>
    /* all your parsed styles in here */
    @font-face {
     font-family: foo;
     src: url('data:application/font-woff;charset=utf-8;base64,...')
    }
  </style>
</defs>

in itself before you do extract its markup.

Leave a Comment