Created
December 22, 2020 17:47
-
-
Save ajiteshsingh/2a5f988c645a344336d5dcb7741a4b7e to your computer and use it in GitHub Desktop.
Extract font names from TTF/OTF/WOFF/WOFF2 files using python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import base64 | |
import io | |
import json | |
import chardet | |
import requests | |
from fontTools import ttLib | |
FONT_SPECIFIER_FAMILY_ID = 1 | |
FONT_SPECIFIER_SUB_FAMILY_ID = 2 | |
def get_font_name(font_file_url: str) -> str: | |
try: | |
r = requests.get(font_file_url) | |
font_meta = ttLib.TTFont(io.BytesIO(r.content)) | |
family, sub_family = "", "" | |
for record in font_meta["name"].names: | |
if record.nameID == FONT_SPECIFIER_SUB_FAMILY_ID and not sub_family: | |
sub_family = extract_name(record.string) | |
elif record.nameID == FONT_SPECIFIER_FAMILY_ID and not family: | |
family = extract_name(record.string) | |
if sub_family and family: | |
break | |
combined_family_sub_family = " ".join((family, sub_family)) | |
if combined_family_sub_family.strip() == "": | |
return None | |
return combined_family_sub_family | |
except Exception as e: | |
log.exception(e) | |
return None |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment