-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathxkcdprint.py
74 lines (67 loc) · 2.73 KB
/
xkcdprint.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#!/usr/bin/env python
"""This script fetches comic(s) from xkcd.com (using xkcd python module) and outputs them to an Epson thermal
printer using the python-escpos module"""
import escpos
import escpos.printer
import xkcd
import textwrap
import sys
import getopt
from random import randint
from PIL import Image
usageText = 'Usage: xkcdprint.py [-n <number of comics to print>] [-r] [-i <comicid>]\nDefaults to printing latest comic.'
nComicsToPrint = 1
nComicsPrinted = 0
comicRandom = False
maxPixelWidth = float(512)
nStartComic = xkcd.getLatestComic().number
try:
opts, args = getopt.getopt(sys.argv[1:], "hn:ri:", ["help", "to-print=", "random", "comicid="])
except getopt.GetoptError:
print(usageText)
sys.exit(2)
for opt, arg in opts:
if opt in ("-h", "--help"):
print(usageText)
sys.exit()
elif opt in ("-r", "--random"):
nStartComic = randint(1, xkcd.getLatestComicNum())
elif opt in ("-i", "--comicid"):
if 0 < int(arg) <= xkcd.getLatestComicNum():
nStartComic = int(arg)
else:
print("Error: Comic ID specified is out of valid range. Please specify a comic ID between 1 and " + str(xkcd.getLatestComicNum()))
sys.exit(1)
elif opt in ("-n", "--to-print"):
nComicsToPrint = int(arg)
print("Printing " + str(nComicsToPrint) + " comics.")
if nComicsToPrint > 1:
print("Comic # " + str(nStartComic) + " and " + str(nComicsToPrint - 1) + " previous comics will be printed.")
else:
print("Comic # " + str(nStartComic) + " selected for printing.")
# Initialize Epson thermal printer using usb-id (here using TM-T20II)
p = escpos.printer.Usb(0x04b8, 0x0e15)
while nComicsPrinted < nComicsToPrint:
comic = xkcd.getComic(nStartComic - nComicsPrinted)
comicImg = comic.download()
comicAltText = textwrap.wrap(comic.getAsciiAltText().decode('utf-8'), 40)
img = Image.open(comicImg.encode('utf-8'))
imgWidth, imgHeight = img.size
if imgWidth > imgHeight and (imgWidth / imgHeight) > 1.4: #handle square-ish images
img = img.rotate(270, expand=True)
imgWidth, imgHeight = img.size
scalingFactor = (maxPixelWidth / min(imgWidth, imgHeight))
elif imgWidth > imgHeight and (imgWidth / imgHeight) <= 1.4:
scalingFactor = (maxPixelWidth / max(imgWidth, imgHeight))
print(scalingFactor)
else:
scalingFactor = (maxPixelWidth / min(imgWidth, imgHeight))
resizedImg = img.resize((int(scalingFactor * imgWidth), int(scalingFactor * imgHeight)))
p.text('\n' + comic.getAsciiTitle().decode('utf-8'))
p.text('\n' + comic.link + '\n\n')
p.image(resizedImg)
p.text('\n')
for line in comicAltText:
p.text('\n' + line)
p.cut()
nComicsPrinted = nComicsPrinted + 1