forked from robbie/devhouse
-
Notifications
You must be signed in to change notification settings - Fork 3
/
print_badge
executable file
·143 lines (116 loc) · 4.96 KB
/
print_badge
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
#!/usr/bin/env python
#
# print_badge
#
# Generates SHDH badges based on a JSON formatted input file.
# Version: Alpha
#
# Copyright (c) 2008, 2009 Joel Franusic, and Adam Marshall Smith
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the "Software"), to deal in the Software without
# restriction, including without limitation the rights to use,
# copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following
# conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
#
# TODO:
# - Give helpful error messages when the configuration file is missing parts that we expect.
# - Add fancypants python documentation
# - Add a library or wrapper for CUPS, send the PNG directly to CUPS
# - Get the job ID from CUPS, wait for the CUPS job to complete before exiting, fail if the CUPS job fails
#
import gd, os, sys, subprocess, getopt, unicodedata, time, simplejson as json
# set the working directory to the actual path of the script
os.chdir(os.path.dirname(os.path.realpath(sys.argv[0])))
CONFIGURATION_FILE = './configuration/print_badge.config.json'
# Shorthand for image positions.
# B = Bottom, T = Top, L = Left, R = Right, X = x, Y = y
(BL_X,BL_Y,BR_X,BR_Y,TL_X,TL_Y,TR_X,TR_Y) = (0,1,2,3,4,5,6,7)
def print_image(file):
print_file = 'lp -d DYMO_LabelWriter_400_USB_1 -o landscape -o fitplot'.split() + [file]
# print_file = 'lp -H test -d DYMO_LabelWriter_400_USB_1 -o landscape -o fitplot'.split() + [file]
opts, args = getopt.getopt(sys.argv[1:], "n") # "no print"
if opts and '-n' in opts[0]:
print "Not executing command:",print_file
else:
subprocess.call(print_file)
# Implement next:
# - Margins: top, bottom, left, right
# - Alignment: left, right, center
def place(image,(x,y),item):
input = {}
input['x'],input['y'],(input['width'],input['height']) = x,y,image.size()
for val in ["x","y","width","height"]:
try: item[val]
except KeyError: pass
if item[val]: input[val] = item[val]
color = image.colorAllocate(item["color"])
im = gd.image((input["width"],input["height"]))
x,y = 0,0 # since we are making a temporary image, set these to origin
# one pass calculation for ideal string size!
size = 100
p = im.get_bounding_rect(item["font"],size,0,(x,y),item["string"])
size = min(
(float(input["width"]) / float(p[BR_X] - p[BL_X]) ) * size, # width ratio
(float(input["height"]) / float(p[BR_Y] - p[TR_Y])) * size # height ratio
)
p = im.get_bounding_rect(item["font"],size,0,(x,y),item["string"])
y += p[TR_Y]*-1
rv = image.string_ttf(item["font"],size,0,(input["x"],input["y"] + y),item["string"],color)
return (input["x"],rv[BR_Y])
def main():
configuration_file = open(CONFIGURATION_FILE)
conf = json.load(configuration_file)
# read card data in from stdin
stdin = sys.stdin.read()
card = json.loads(stdin)
# merge in the card data we just got from STDIN into the default configuration
for key,value in card.iteritems():
if conf.has_key(key):
conf[key]["string"] = value
conf["badge"]["file"] = ''.join(('./completed/',card["key"],"_shdh",card["shdh_number"],'.png'))
try: conf["badge"]["remove_accents"]
except NameError: conf["badge"]["remove_accents"] = None
os.environ["GDFONTPATH"] = conf["badge"]["font_path"]
im = gd.image((conf["badge"]["width"],conf["badge"]["height"]))
white = im.colorAllocate(conf["badge"]["color"])
x,y = 0,0
for item in conf["badge"]["design"]:
# There has to be a better way to test for if a variable is defined
try: conf[item]["string"]
except KeyError: conf[item]["string"] = None
try: conf[item]["file"]
except KeyError: conf[item]["file"] = None
if conf[item]["string"]:
if conf["badge"]["remove_accents"]:
conf[item]["string"] = unicodedata.normalize('NFKD', conf[item]["string"]).encode('ascii','ignore')
(x,y) = place(im,(x,y),conf[item])
elif conf[item]["file"]:
temporary = gd.image(conf[item]["file"])
temporary.copyTo(im,(conf[item]["x"],conf[item]["y"]))
else:
print "ERROR"
badge=open(conf["badge"]["file"],"w")
im.writePng(badge)
badge.close()
print_image(conf["badge"]["file"])
if __name__ == "__main__":
# t1 = time.time()
main()
# t2 = time.time()
# print 'took %0.3f ms' % ((t2-t1)*1000.0)