1

I have read and tried several threads, but I was unable to solve this problem.

I have a simple SVG file:

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 289 144.94">
    <defs>
        <style type="text/css">
            @import url('https://fonts.googleapis.com/css2?family=Cabin:ital,wght@0,400;0,500;0,600;0,700;1,400;1,500;1,600;1,700');
        </style>
        <style type="text/css">
            @import url('https://fonts.googleapis.com/css2?family=Cabin:ital,wght@0,400;0,500;0,600;0,700;1,400;1,500;1,600;1,700');
        </style>
        <style type="text/css">.cls-11{font-size:53.58px;}
        </style>
    </defs>
    <text class="cls-11" textLength="110" lengthAdjust="spacingAndGlyphs" transform="translate(160.98 45.54)">M2/1</text>
</svg>

But I'm unable to generate a PNG output for this SVG in Python. I have tried cairosvg, pyvips, wandpy, but all had some sort of issues. Mainly the 2 problem:

  • The imported font is not loaded/not recognized.
  • The lenghtAdjust parameter seems to be ignored by most of them.

It would be also acceptable for me to generate another pixel-based format from this or use another programming language/library.

Kristof Rado
  • 713
  • 1
  • 8
  • 19
  • The same question has been asked here https://stackoverflow.com/questions/6589358/convert-svg-to-png-in-python @Kristof Rado you can follow this link and look for one of the good upvoted answers – Nwawel A Iroume Apr 06 '22 at 09:06
  • Please check my response in the answer provided which has the same link as yours. This does not solve my problem with fonts and additional svg attributes like 'lengthAdjust' – Kristof Rado Apr 06 '22 at 09:12

1 Answers1

-1
from cairosvg import svg2png

from cairosvg import svg2png

svg_code = """
    <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#000" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
        <circle cx="12" cy="12" r="10"/>
        <line x1="12" y1="8" x2="12" y2="12"/>
        <line x1="12" y1="16" x2="12" y2="16"/>
    </svg>
"""

svg2png(bytestring=svg_code,write_to='output.png')

this example was given by a user called "JWL", does the below link answer your question?

Convert SVG to PNG in Python

  • No it won't work on my example. The font is not loaded (default font is used) and the lenghtAdjust parameter is ignored (text is outside of viewBox if the text is longer). – Kristof Rado Apr 06 '22 at 08:09
  • This was downvoted because it does not address how to port a font into the svg to be outputted in the png. – Shmack Dec 14 '22 at 07:31