SVG
SVG copied to clipboard
Font support when rendering to PNG
Description
I'm using the SVG.NET library to convert SVG to PNG and I have an issue with wrong font being picked. Here is a simple example to explain my issue:
<svg width="500" height="500" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<style>
@import url('https://fonts.googleapis.com/css2?family=Rubik:wght@400;500');
</style>
<text font-family="Rubik" font-size="28px" font-weight="400" x="250" y="40" text-anchor="middle">Font-Weight 400</text>
<text font-family="Rubik" font-size="28px" font-weight="500" x="250" y="100" text-anchor="middle">Font-Weight 500</text>
</svg>
I initially found out that the @import above isn't supported so I just got the default font. I worked around that by preprocessing the SVG-file looking for @import statements and downloading respective .ttf font files to a local folder.
The above import returns two files:
src: url(https://fonts.gstatic.com/s/rubik/v14/iJWZBXyIfDnIV5PNhY1KTN7Z-Yh-B4i1UA.ttf) format('truetype');
src: url(https://fonts.gstatic.com/s/rubik/v14/iJWZBXyIfDnIV5PNhY1KTN7Z-Yh-NYi1UA.ttf) format('truetype');
After downloading them I call:
SvgFontManager.PrivateFontPathList.AddRange(fontsJustDownloaded);
Then I convert the SVG to PNG. This works fine, but both lines in the SVG above are rendered using the same font style.
💡
While grabbing all relevant information for this issue I see that the .ttf files I've downloaded have different names when opening with the standard Windows file dialog (Rubik
, Rubik Medium
) and the PNG conversion works if I replace the font-family in the second line with "Rubik Medium".
I now think I see a workaround to the issue but I'm leaving the issue here for pointers in case I'm going about this the wrong way.
The file https://fonts.googleapis.com/css2?family=Rubik:wght@400;500 also contains weight information so I guess I can extend my pre-processing and replace the font-family based on the font-family and font-weight.
@font-face {
font-family: 'Rubik';
font-style: normal;
font-weight: 400;
font-display: swap;
src: url(https://fonts.gstatic.com/s/rubik/v14/iJWZBXyIfDnIV5PNhY1KTN7Z-Yh-B4i1UA.ttf) format('truetype');
}
@font-face {
font-family: 'Rubik';
font-style: normal;
font-weight: 500;
font-display: swap;
src: url(https://fonts.gstatic.com/s/rubik/v14/iJWZBXyIfDnIV5PNhY1KTN7Z-Yh-NYi1UA.ttf) format('truetype');
}
So basically find the Windows font-name for each of the downloaded files and replace the font-family in the SVG with this name instead of the generic name.
Example data
Used Versions
Svg 3.3.0 .NET Framework 4.6.1