Skip to content

Instantly share code, notes, and snippets.

Last active May 13, 2021 06:14
What would you like to do?
Give it a <link> from Google fonts and get back CSS with fonts embedded
# encoding: utf-8
# Grab google web fonts and embed them as base64 data URIs
# <>
require 'base64'
if ARGV.length > 0
input = ARGV
elsif STDIN.stat.size > 0
input =\n+/)
$stderr.puts "No input"
Process.exit 1
output = ""
input.each {|line|
if line =~ /^\s*<link.*?>\s*$/
url = line.match(/href='(.*?)'/)
if url
css_url = url[1]
$stderr.puts "Error matching url"
css = %x{curl -sS '#{css_url}'}.strip
css.gsub!(/(src: .*?, url\()(.*?)(\) format\(')(.*?)('\);)/).each {|src|
pre = $1
font_url = $2
mid = $3
font_fmt = $4
post = $5
font_ext = font_url.match(/\.(\w+)$/)[1]
font_src = %x{curl -sS '#{font_url}'}
enc = Base64.encode64(font_src).strip.gsub(/\n/,'')
%Q{src:url("data:font/#{font_ext};base64,#{enc}") format('#{font_fmt}');}
output += css + "\n"
$stdout.puts output
Copy link

for all windows users. you need to change the quotes to double quotes for curl.

so change line 27 and 36 and instead of curl -sS 'XXXX' use curl -sS "XXX"

Copy link


Copy link

ideaOwl commented Aug 24, 2016

Syntax to run this on Windows, to add on top of @eikaramba's change, is:

ruby font_grabber.rb "<link href=',400,700' rel='stylesheet'>" > fonts.css

Copy link

You will want to change to change the regex on line 20 support double quotes.


Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment