问题
I'm using Cairo/RSVG based solution for rasterizing SVG to PNG. It's already beeb described on StackOverflow in Convert SVG to PNG in Python. However, this solution doesn't seem to work with custom fonts.
I've found this page describing embedding SVG fonts.
I've tried to include them from external SVG via XLink, as described in example. I've tried embedding the font directly in the same SVG file. Having failed with that, I've tried CSS Web Fonts syntax. None of the 3 methods works when rendering with Cairo (nor does it work in the Ubuntu's default viewer Eye of GNOME).
I've tried ImageMagick, with exactly same results as Cairo.
On the other hand with all 3 font embedding methods, fonts are rendered fine in WebKit, either using Google Chrome or webkit2png.py. However, if possible I'd like to avoid using QT WebKit on server, as it's non-trivial setup (including xvfb etc.), and I'm afraid that might not result very efficient nor stable.
Is there any alternative method of rendering SVG to PNG from Python?
回答1:
I have spent a week researching this very issue and concluded that the best way to handle server-side rendering/rasterizing of SVG with custom fonts is to install those fonts on the server. The tools I tried (rsvg, imagemagick, phantomjs, qtwebkit...) could not handle web fonts and svg fonts.
Google has several hundred fonts (and growing) that one can download and use on a server.
- Download OTF or TTF fonts
- Install them on the server and refresh the font cache
- Replace the CSS definitions of the external fonts with font family names in your SVG docs.
And if you also need to use those same fonts in a web page, you could link to Google CDN directly for the WOFF files to conserve your own server time and network bandwidth.
回答2:
You can try to use inkscape, perhaps this gives you better results:
inkscape inputfile.svg --export-png=exportfile.png
Running this from python is described here: Calling an external command in Python
回答3:
With Imagemagick I still struggle with svg rasterizing with fonts that are installed on the server and can be used in certain operations, but fail when using -convert from .svg to .png.... It seems to turn every type of text into arial. I think it may be a bug with ImageMagick or a certain format needed in the .svg
回答4:
A couple of things to check with RSVG:
- That the font source files are in your system or user font path
- That font names in the SVG are not quoted, even if they contain spaces. librsvg will assume the quotes are part of the font name and it won't find the source files.
来源:https://stackoverflow.com/questions/7321113/svg-to-png-with-custom-fonts-in-python