Home > Net >  How to get font path from font name [python]?
How to get font path from font name [python]?

Time:02-02

My aim is to get the font path from their common font name and then use them with PIL.ImageFont.

I got the names of all installed fonts by using tkinter.font.families(), but I want to get the full path of each font so that I can use them with PIL.ImageFont. Is there any other way to use the common font name with ImageFont.truetype() method?

CodePudding user response:

I'm not exactly sure what you really want - but here is a way to get a list of the full path to all the fonts on your system and their names and weights:

#!/usr/bin/env python3

import matplotlib.font_manager
from PIL import ImageFont

# Iterate over all font files known to matplotlib
for filename in matplotlib.font_manager.findSystemFonts(): 
    # Avoid these two trouble makers - don't know why they are problematic
    if "Emoji" not in filename and "18030" not in filename:
        # Look up what PIL knows about the font
        font = ImageFont.FreeTypeFont(filename)
        name, weight = font.getname()
        print(f'File: {filename}, fontname: {name}, weight: {weight}')

Sample Output

File: /System/Library/Fonts/Supplemental/NotoSansLepcha-Regular.ttf, fontname: Noto Sans Lepcha, weight: Regular
File: /System/Library/Fonts/ZapfDingbats.ttf, fontname: Zapf Dingbats, weight: Regular
File: /System/Library/Fonts/Supplemental/Zapfino.ttf, fontname: Zapfino, weight: Regular
File: /System/Library/Fonts/Supplemental/NotoSansMultani-Regular.ttf, fontname: Noto Sans Multani, weight: Regular
File: /System/Library/Fonts/Supplemental/NotoSansKhojki-Regular.ttf, fontname: Noto Sans Khojki, weight: Regular
File: /System/Library/Fonts/Supplemental/Mishafi Gold.ttf, fontname: Mishafi Gold, weight: Regular
File: /System/Library/Fonts/Supplemental/NotoSansMendeKikakui-Regular.ttf, fontname: Noto Sans Mende Kikakui, weight: Regular
File: /System/Library/Fonts/MuktaMahee.ttc, fontname: Mukta Mahee, weight: Regular
File: /Users/mark/Library/Fonts/JetBrainsMonoNL-Italic.ttf, fontname: JetBrains Mono NL, weight: Italic
...
...
  • Related