Picnic Projects

Sunday afternoon tinkering

Font Sample Generator

Through the years, I’ve collected over 1000 fonts (mostly TTF). Whenever I need one, I’d like to be able to browse through all of them easily. So far, I didn’t find a software package that is both quick and easy. Therefore, I made a small python script that generates a single html file with samples of all fonts in a directory and its subdirectories. The python script uses the Python Imaging Library (Pillow).

I pasted a screenshot of a small part of the html file:

from PIL import ImageFont, ImageDraw, Image
import os

def makedir(d):
   try:
      os.mkdir(d)
   except:
      pass

def get_first(s):
   f = s[0].upper()
   if not f.isalpha():
      f = '#'
   return(f)
   
def font2jpg(font_full_filename, jpg_full_filename):
   font = ImageFont.truetype(font=font_full_filename, size=42)
   image = Image.new(mode='RGB', size=(1024, 60), color='#ffffff')
   draw = ImageDraw.Draw(im=image)
   draw.text(xy=(0,0), text="The Quick Brown Fox jumps over the Lazy Dog", font=font, fill='black')
   image.save(jpg_full_filename)

source_dir  = '.'
target_dir  = 'c:/temp/myfonts'
jpg_sub_dir = 'img'
jpg_dir     = target_dir + '/' + jpg_sub_dir
makedir(target_dir)
makedir(jpg_dir)
fid = open(target_dir + "/index.html", "w")
fid.write("<html><head><style>body {font-family: Arial, sans-serif;}</style></head><body>\n")
fid.write("<table>\n")
i = 0
allowed_ext = ['eot', 'ttc', 'ttf', 'otf']
for root, dirs, files in os.walk(source_dir):
   for fname in files:
      ext = fname.lower().split('.')[-1]
      if ext in allowed_ext:
         font_full_filename = root + '/' + fname
         print(font_full_filename)
         first_character_of_font = get_first(fname)
         makedir(jpg_dir + '/' + first_character_of_font)
         jpg_short_filename  = jpg_sub_dir + '/' + first_character_of_font + '/' + fname + '.jpg'
         try:
            font2jpg(font_full_filename, target_dir + '/' + jpg_short_filename)
            i = i + 1 
            fid.write("<tr><td>%d</td><td><a href='%s'>%s</a></td><td><img src='%s'></td></tr>\n" % (i, font_full_filename ,fname, jpg_short_filename))
         except Exception as error:
            print("*** An exception occurred:", type(error).__name__, "–", error,"(",fname,")")
fid.write("</table>")
fid.write("</body>")
fid.write("</html>")
fid.close()