I'm trying to render SVG out of an unicode using Python's fonttools:
from fontTools.ttLib import TTFont
from fontTools.pens.svgPathPen import SVGPathPen
def unicode_to_svg(unicode_char, font_path, output_svg_path):
# Load the TTF font using fonttools
font = TTFont(font_path)
# Get the glyph index for the Unicode character
glyph_index = font.getGlyphID(unicode_char)
# Convert the glyph to an SVG path
glyph_set = font.getGlyphSet()
glyph_name = font.getGlyphName(glyph_index)
glyph = glyph_set[glyph_name]
pen = SVGPathPen(glyph_set)
glyph.draw(pen)
svg_path_data = pen.getCommands()
# Create the SVG content
svg_content = f'''
<svg width="3000" height="3000" xmlns="http://www.w3.org/2000/svg">
<path d="{svg_path_data}" fill="red" />
</svg>
'''
# Save the SVG content to a file
with open(output_svg_path, 'w') as f:
f.write(svg_content)
# Example usage
font_path = './Nikosh.ttf'
# unicode_char = 'A'
unicode_char = 'ম'
output_svg_path = 'output.svg'
unicode_to_svg(unicode_char, font_path, output_svg_path)
But the issue is, it works fine for English alphabets. But when I try to render unicode (such as Bengali) it gives me:
KeyError: 'ম'
On this line: glyph_index = font.getGlyphID(unicode_char)
I simply wanted to take a deeper dive into SVG rendering of different languages, fonts, texts, etc.
How can I resolve this issue? And make it SVG render-able for any unicode character?
The function
char_in_fontcomes from my another project, included here unmodified… Check its output before passing togetGlyphID.Output: