# Simple script for rendring texts with fixed-width fonts stored as image.
#
# by drummyfish
# CC0 1.0, public domain

import sys
from PIL import Image

FONT_FILE = sys.argv[1]
HORIZONTAL_SPACE = int(sys.argv[2])
VERTICAL_SPACE = int(sys.argv[3])
TEXT_FILE = sys.argv[4]

textFile = open(TEXT_FILE,"r")
text = textFile.read()
textFile.close()

textSize = [0,0]

lineLen = 0

for c in text:
  if lineLen == 0:
    textSize[1] += 1

  if c == "\n":
    textSize[0] = max(lineLen,textSize[0])
    lineLen = 0
  else:
    lineLen += 1

font = Image.open(FONT_FILE).convert("RGB")
pixels = font.load()

charSize = (font.size[0] / 94, font.size[1])

out = Image.new("RGB",(textSize[0] * (charSize[0] + HORIZONTAL_SPACE),textSize[1] * (charSize[1] + VERTICAL_SPACE)),color="white")
pixels2 = out.load()

pos = [0,0]

for c in text:
  o = ord(c)

  if o < 31 or o > 127:
    o = ord("?")

  fontX = (o - 32) * charSize[0]

  if c != "\n":
    for y in range(charSize[1]):
      for x in range(charSize[0]):
        pixels2[pos[0] + x,pos[1] + y] = pixels[fontX + x,y] 

    pos[0] += charSize[0] + HORIZONTAL_SPACE
  else:
    pos = [0,pos[1] + charSize[1] + VERTICAL_SPACE]

out.save("out.png")

