Skip to content

Instantly share code, notes, and snippets.

@leoleozhu
Created August 16, 2019 14:41
Show Gist options
  • Save leoleozhu/80e870470f8a0dc25e7005656e8b00ff to your computer and use it in GitHub Desktop.
Save leoleozhu/80e870470f8a0dc25e7005656e8b00ff to your computer and use it in GitHub Desktop.
Get FontFamily, Styles from a TTFont object (python fonttools lib)
class TTFontInfo(object):
bold_names = ("bold", "demibold", "demi-bold", "demi bold", "negreta", "demi",)
italic_names = ("italic", "cursiva", "oblique", "inclined",)
bold_italic_names = ("bolditalic", "bold-italic", "bold italic", "boldoblique", "bold-oblique",
"bold oblique", "demibold italic", "negreta cursiva", "demi oblique",)
font_specifier_family_id = 1
font_specifier_sub_family_id = 2
def __init__(self, family_name, is_bold=False, is_italic=False):
self._family_name = family_name
self._is_bold = is_bold
self._is_italic = is_italic
@property
def family_name(self):
return self._family_name
@property
def is_bold(self):
return self._is_bold
@property
def is_italic(self):
return self._is_italic
@classmethod
def from_ttfont(cls, tt_font):
family = ""
sub_family = ""
name_table = tt_font['name']
for record in name_table.names:
name_str = record.toUnicode()
if record.nameID == cls.font_specifier_family_id and not family:
family = name_str
elif record.nameID == cls.font_specifier_sub_family_id and not sub_family:
sub_family = name_str
if family and sub_family:
break
is_bold = False
is_italic = False
sub_family_lower = sub_family.lower()
if any([n in sub_family_lower for n in cls.bold_italic_names]):
is_bold = True
is_bold = True
if any([n in sub_family_lower for n in cls.bold_names]):
is_bold = True
if any([n in sub_family_lower for n in cls.italic_names]):
is_italic = True
return TTFontInfo(family, is_bold=is_bold, is_italic=is_italic)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment