Skip to content

Instantly share code, notes, and snippets.

@treystout
Created December 7, 2015 21:37
Show Gist options
  • Save treystout/0b1d001447dc9b0d2ff9 to your computer and use it in GitHub Desktop.
Save treystout/0b1d001447dc9b0d2ff9 to your computer and use it in GitHub Desktop.
Generates a PNG of every handwriting from Handwriting.io
#!/usr/bin/env python
"""This script simply renders a message as a pdf and saves it to a file
(out.pdf) in the working directory
"""
import os
import sys
try:
import requests
except ImportError:
print "This script requires the requests library which can be downloaded at "\
"http://docs.python-requests.org/en/latest/"
sys.exit(1)
BASE_URL = "https://api.handwriting.io"
API_TOKEN = "<YOUR TOKEN>"
API_SECRET = "<YOUR SECRET>"
OUT_DIRECTORY = "out"
# this is the message we will turn into handwriting. It supports most
# white-space characters such as newline (\n) and tab (\t) as well as
# regular spaces
message = ("This is a writing sample written in %s."
"\n\nThe next sentence is a pangram (it contains every letter used in "
"english all in a single sentence!)\n\nAmazingly few discotheques "
"provide jukeboxes.\n\n\t-Benjamin Franklin")
# get list of handwritings...
r = requests.get("%s%s" % (BASE_URL, "/handwritings"),
auth=(API_TOKEN, API_SECRET))
r.raise_for_status()
handwritings = r.json()
# now loop over them, render a message in each one, and save it to a file named
# after the handwriting
for hw in handwritings:
# this is the actual rendering request for a PNG.
r = requests.get("%s%s" % (BASE_URL, "/render/png"),
auth=(API_TOKEN, API_SECRET),
params={
'text': message % hw['title'],
'handwriting_id': hw['id'], # find more ids at /handwritings
'handwriting_size': 'auto',
'height': '400px',
'width': '600px'
},
stream=True # to prevent in-memory buffering of the image
)
r.raise_for_status()
filename = os.path.join(OUT_DIRECTORY, '%s.png' % hw['title'])
with open(filename, 'wb') as f:
for chunk in r.iter_content(chunk_size=4096):
f.write(chunk)
print "results written to %s" % filename
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment