Skip to content

Instantly share code, notes, and snippets.

@ntrrgc
Last active August 29, 2015 14:06
Show Gist options
  • Save ntrrgc/713c85f55d8f06bc1521 to your computer and use it in GitHub Desktop.
Save ntrrgc/713c85f55d8f06bc1521 to your computer and use it in GitHub Desktop.
Download Google fonts
#!/usr/bin/python3
# TODO: Does not support woff2 fonts (as served for Chrome)
import os, sys, re
import requests
def fetch_fonts(input_css, font_path="fonts"):
output_css = []
for line in input_css.split("\n"):
if "https://" in line:
name = re.match(r".*local\('(.*?)'\).*", line).groups()[0]
url = re.match(r".*url\((.*?)\).*", line).groups()[0]
local_name = name.replace(" ", "-").lower() + "." + \
url.split(".")[-1]
if os.path.exists(local_name):
print("Skipping %s (already downloaded)." % local_name)
else:
print("Downloading %s..." % local_name)
with open(local_name, "wb") as f:
f.write(requests.get(url).content)
new_line = re.sub(r"url\(.*?\)", "url(%s)" %
os.path.join(font_path, local_name), line)
else:
new_line = line
output_css.append(new_line)
return "\n".join(output_css)
if __name__ == "__main__":
from argparse import ArgumentParser
parser = ArgumentParser(description=
"Fetch fonts from Google Font CSS files. "
"You must enter Google CSS as stdin.")
parser.add_argument("--font-path", dest="font_path",
default="fonts", type=str,
help="The path prefix where fonts will be accessed by "
"the browser")
args = parser.parse_args()
input_css = sys.stdin.read()
output_css = fetch_fonts(input_css, args.font_path)
print(output_css)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment