forked from pklaus/brother_ql_web
-
Notifications
You must be signed in to change notification settings - Fork 0
/
brother_ql_web.py
executable file
·407 lines (329 loc) · 14.9 KB
/
brother_ql_web.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
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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This is a web service to print labels on Brother QL label printers.
"""
import sys, logging, random, json, argparse, time, datetime
from io import BytesIO
from bottle import run, route, get, post, response, request, jinja2_view as view, static_file, redirect
from PIL import Image, ImageDraw, ImageFont
from brother_ql.devicedependent import models, label_type_specs, label_sizes
from brother_ql.devicedependent import ENDLESS_LABEL, DIE_CUT_LABEL, ROUND_DIE_CUT_LABEL
from brother_ql import BrotherQLRaster, create_label
from brother_ql.backends import backend_factory, guess_backend
from font_helpers import get_fonts
logger = logging.getLogger(__name__)
LABEL_SIZES = [ (name, label_type_specs[name]['name']) for name in label_sizes]
try:
with open('config.json', encoding='utf-8') as fh:
CONFIG = json.load(fh)
except FileNotFoundError as e:
with open('config.example.json', encoding='utf-8') as fh:
CONFIG = json.load(fh)
@route('/')
def index():
redirect('/labeldesigner')
@route('/static/<filename:path>')
def serve_static(filename):
return static_file(filename, root='./static')
@route('/labeldesigner')
@view('labeldesigner.jinja2')
def labeldesigner():
font_family_names = sorted(list(FONTS.keys()))
return {'font_family_names': font_family_names,
'fonts': FONTS,
'label_sizes': LABEL_SIZES,
'website': CONFIG['WEBSITE'],
'label': CONFIG['LABEL']}
def get_label_context(request):
""" might raise LookupError() """
d = request.params.decode() # UTF-8 decoded form data
font_family = d.get('font_family').rpartition('(')[0].strip()
font_style = d.get('font_family').rpartition('(')[2].rstrip(')')
context = {
'text': d.get('text', None),
'font_size': int(d.get('font_size', 100)),
'font_family': font_family,
'font_style': font_style,
'label_size': d.get('label_size', "62"),
'kind': label_type_specs[d.get('label_size', "62")]['kind'],
'margin': int(d.get('margin', 10)),
'threshold': int(d.get('threshold', 70)),
'align': d.get('align', 'center'),
'orientation': d.get('orientation', 'standard'),
'margin_top': float(d.get('margin_top', 24))/100.,
'margin_bottom': float(d.get('margin_bottom', 45))/100.,
'margin_left': float(d.get('margin_left', 35))/100.,
'margin_right': float(d.get('margin_right', 35))/100.,
'cut': d.get('cut', 'true').lower() == 'true',
'visitor': d.get('visitor', None),
'employee': d.get('employee', None),
}
context['margin_top'] = int(context['font_size']*context['margin_top'])
context['margin_bottom'] = int(context['font_size']*context['margin_bottom'])
context['margin_left'] = int(context['font_size']*context['margin_left'])
context['margin_right'] = int(context['font_size']*context['margin_right'])
context['fill_color'] = (255, 0, 0) if 'red' in context['label_size'] else (0, 0, 0)
def get_font_path(font_family_name, font_style_name):
try:
if font_family_name is None or font_style_name is None:
font_family_name = CONFIG['LABEL']['DEFAULT_FONTS']['family']
font_style_name = CONFIG['LABEL']['DEFAULT_FONTS']['style']
font_path = FONTS[font_family_name][font_style_name]
except KeyError:
raise LookupError("Couln't find the font & style")
return font_path
context['font_path'] = get_font_path(context['font_family'], context['font_style'])
def get_label_dimensions(label_size):
try:
ls = label_type_specs[context['label_size']]
except KeyError:
raise LookupError("Unknown label_size")
return ls['dots_printable']
width, height = get_label_dimensions(context['label_size'])
if height > width: width, height = height, width
if context['orientation'] == 'rotated': height, width = width, height
context['width'], context['height'] = width, height
return context
def create_visitor_label(font_path, visitor, employee):
"""
Create a label for a visitor
Note that this is fixed width and height for 62mm labels.
"""
width, height = 696, 480 # FIXME: hardcoded for 62mm labels
img = Image.new('RGB', (width, height), 'white')
d = ImageDraw.Draw(img)
offset_vertical = 10
font = ImageFont.truetype(font_path, 100)
title_text = "GESTUR" # Icelandic for "Visitor"
title_width, title_height = d.textbbox((0, 0), title_text, font=font)[2:]
d.text(((width - title_width) / 2, offset_vertical), title_text, fill="black", font=font)
offset_vertical += title_height + 55
# Dynamically adjust font size to fit the label width
font_size = 84
while True:
visitor_font = ImageFont.truetype(font_path, font_size)
visitor_width, visitor_height = d.textbbox((0, 0), visitor, font=visitor_font)[2:]
if visitor_width < (width - 50):
break
font_size -= 1
d.text(((width - visitor_width) / 2, offset_vertical), visitor, fill="black", font=visitor_font)
offset_vertical += visitor_height + 75
employee_header = "Ábyrgðaraðili er"
employee_header_font = ImageFont.truetype(font_path, 32)
employee_width, employee_height = d.textbbox((0, 0), employee_header, font=employee_header_font)[2:]
d.text(((width - employee_width) / 2, offset_vertical), employee_header, fill="black", font=employee_header_font)
offset_vertical += employee_height + 10
employee_font = ImageFont.truetype(font_path, 32)
employee_width, employee_height = d.textbbox((0, 0), employee, font=employee_font)[2:]
d.text(((width - employee_width) / 2, offset_vertical), employee, fill="black", font=employee_font)
offset_vertical += employee_height + 30
date = datetime.datetime.now().strftime("%d.%m.%Y %H:%M")
date_font = ImageFont.truetype(font_path, 32)
date_width, date_height = d.textbbox((0, 0), date, font=date_font)[2:]
d.text(((width - date_width) / 2, offset_vertical), date, fill="black", font=date_font)
return img
def create_label_im(text, **kwargs):
label_type = kwargs['kind']
im_font = ImageFont.truetype(kwargs['font_path'], kwargs['font_size'])
im = Image.new('L', (20, 20), 'white')
draw = ImageDraw.Draw(im)
# workaround for a bug in multiline_textsize()
# when there are empty lines in the text:
lines = []
for line in text.split('\n'):
if line == '': line = ' '
lines.append(line)
text = '\n'.join(lines)
linesize = im_font.getbbox(text)[-2:]
textsize = draw.multiline_textsize(text, font=im_font)
width, height = kwargs['width'], kwargs['height']
if kwargs['orientation'] == 'standard':
if label_type in (ENDLESS_LABEL,):
height = textsize[1] + kwargs['margin_top'] + kwargs['margin_bottom']
elif kwargs['orientation'] == 'rotated':
if label_type in (ENDLESS_LABEL,):
width = textsize[0] + kwargs['margin_left'] + kwargs['margin_right']
im = Image.new('RGB', (width, height), 'white')
draw = ImageDraw.Draw(im)
if kwargs['orientation'] == 'standard':
if label_type in (DIE_CUT_LABEL, ROUND_DIE_CUT_LABEL):
vertical_offset = (height - textsize[1])//2
vertical_offset += (kwargs['margin_top'] - kwargs['margin_bottom'])//2
else:
vertical_offset = kwargs['margin_top']
horizontal_offset = max((width - textsize[0])//2, 0)
elif kwargs['orientation'] == 'rotated':
vertical_offset = (height - textsize[1])//2
vertical_offset += (kwargs['margin_top'] - kwargs['margin_bottom'])//2
if label_type in (DIE_CUT_LABEL, ROUND_DIE_CUT_LABEL):
horizontal_offset = max((width - textsize[0])//2, 0)
else:
horizontal_offset = kwargs['margin_left']
offset = horizontal_offset, vertical_offset
draw.multiline_text(offset, text, kwargs['fill_color'], font=im_font, align=kwargs['align'])
return im
@get('/api/preview/text')
@post('/api/preview/text')
def get_preview_image():
context = get_label_context(request)
im = create_label_im(**context)
return_format = request.query.get('return_format', 'png')
if return_format == 'base64':
import base64
response.set_header('Content-type', 'text/plain')
return base64.b64encode(image_to_png_bytes(im))
else:
response.set_header('Content-type', 'image/png')
return image_to_png_bytes(im)
def image_to_png_bytes(im):
image_buffer = BytesIO()
im.save(image_buffer, format="PNG")
image_buffer.seek(0)
return image_buffer.read()
@get('/api/print/visitorpass')
@post('/api/print/visitorpass')
def print_visitor_pass():
"""
API to print visitor pass
returns: JSON
"""
return_dict = {'success': True}
try:
context = get_label_context(request)
except LookupError as e:
return_dict['error'] = e.msg
return return_dict
if context['visitor'] is None:
return_dict['error'] = 'Please provide visitor name'
return return_dict
if context['employee'] is None:
return_dict['error'] = 'Please provide employee responsible for the visit'
return return_dict
im = create_visitor_label(context['font_path'], context['visitor'], context['employee'])
if DEBUG: im.save('sample-out.png')
if context['kind'] == ENDLESS_LABEL:
rotate = 0 if context['orientation'] == 'standard' else 90
elif context['kind'] in (ROUND_DIE_CUT_LABEL, DIE_CUT_LABEL):
rotate = 'auto'
qlr = BrotherQLRaster(CONFIG['PRINTER']['MODEL'])
red = 'red' in context['label_size']
create_label(qlr, im, context['label_size'], red=red, threshold=context['threshold'], cut=context['cut'], rotate=rotate)
if not DEBUG:
try:
be = BACKEND_CLASS(CONFIG['PRINTER']['PRINTER'])
be.write(qlr.data)
be.dispose()
del be
except Exception as e:
return_dict['message'] = str(e)
logger.warning('Exception happened: %s', e)
return return_dict
return return_dict
@post('/api/print/text')
@get('/api/print/text')
def print_text():
"""
API to print a label
returns: JSON
Ideas for additional URL parameters:
- alignment
"""
return_dict = {'success': False}
try:
context = get_label_context(request)
except LookupError as e:
return_dict['error'] = e.msg
return return_dict
if context['text'] is None:
return_dict['error'] = 'Please provide the text for the label'
return return_dict
im = create_label_im(**context)
if DEBUG: im.save('sample-out.png')
if context['kind'] == ENDLESS_LABEL:
rotate = 0 if context['orientation'] == 'standard' else 90
elif context['kind'] in (ROUND_DIE_CUT_LABEL, DIE_CUT_LABEL):
rotate = 'auto'
qlr = BrotherQLRaster(CONFIG['PRINTER']['MODEL'])
red = False
if 'red' in context['label_size']:
red = True
create_label(qlr, im, context['label_size'], red=red, threshold=context['threshold'], cut=context['cut'], rotate=rotate)
if not DEBUG:
try:
be = BACKEND_CLASS(CONFIG['PRINTER']['PRINTER'])
be.write(qlr.data)
be.dispose()
del be
except Exception as e:
return_dict['message'] = str(e)
logger.warning('Exception happened: %s', e)
return return_dict
return_dict['success'] = True
if DEBUG: return_dict['data'] = str(qlr.data)
return return_dict
def main():
global DEBUG, FONTS, BACKEND_CLASS, CONFIG
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--port', default=False)
parser.add_argument('--loglevel', type=lambda x: getattr(logging, x.upper()), default=False)
parser.add_argument('--font-folder', default=False, help='folder for additional .ttf/.otf fonts')
parser.add_argument('--default-label-size', default=False, help='Label size inserted in your printer. Defaults to 62.')
parser.add_argument('--default-orientation', default=False, choices=('standard', 'rotated'), help='Label orientation, defaults to "standard". To turn your text by 90°, state "rotated".')
parser.add_argument('--model', default=False, choices=models, help='The model of your printer (default: QL-500)')
parser.add_argument('printer', nargs='?', default=False, help='String descriptor for the printer to use (like tcp://192.168.0.23:9100 or file:///dev/usb/lp0)')
args = parser.parse_args()
if args.printer:
CONFIG['PRINTER']['PRINTER'] = args.printer
if args.port:
PORT = args.port
else:
PORT = CONFIG['SERVER']['PORT']
if args.loglevel:
LOGLEVEL = args.loglevel
else:
LOGLEVEL = CONFIG['SERVER']['LOGLEVEL']
if LOGLEVEL == 'DEBUG':
DEBUG = True
else:
DEBUG = False
if args.model:
CONFIG['PRINTER']['MODEL'] = args.model
if args.default_label_size:
CONFIG['LABEL']['DEFAULT_SIZE'] = args.default_label_size
if args.default_orientation:
CONFIG['LABEL']['DEFAULT_ORIENTATION'] = args.default_orientation
if args.font_folder:
ADDITIONAL_FONT_FOLDER = args.font_folder
else:
ADDITIONAL_FONT_FOLDER = CONFIG['SERVER']['ADDITIONAL_FONT_FOLDER']
logging.basicConfig(level=LOGLEVEL)
try:
selected_backend = guess_backend(CONFIG['PRINTER']['PRINTER'])
except ValueError:
parser.error("Couln't guess the backend to use from the printer string descriptor")
BACKEND_CLASS = backend_factory(selected_backend)['backend_class']
if CONFIG['LABEL']['DEFAULT_SIZE'] not in label_sizes:
parser.error("Invalid --default-label-size. Please choose on of the following:\n:" + " ".join(label_sizes))
FONTS = get_fonts()
if ADDITIONAL_FONT_FOLDER:
FONTS.update(get_fonts(ADDITIONAL_FONT_FOLDER))
if not FONTS:
sys.stderr.write("Not a single font was found on your system. Please install some or use the \"--font-folder\" argument.\n")
sys.exit(2)
for font in CONFIG['LABEL']['DEFAULT_FONTS']:
try:
FONTS[font['family']][font['style']]
CONFIG['LABEL']['DEFAULT_FONTS'] = font
logger.debug("Selected the following default font: {}".format(font))
break
except: pass
if CONFIG['LABEL']['DEFAULT_FONTS'] is None:
sys.stderr.write('Could not find any of the default fonts. Choosing a random one.\n')
family = random.choice(list(FONTS.keys()))
style = random.choice(list(FONTS[family].keys()))
CONFIG['LABEL']['DEFAULT_FONTS'] = {'family': family, 'style': style}
sys.stderr.write('The default font is now set to: {family} ({style})\n'.format(**CONFIG['LABEL']['DEFAULT_FONTS']))
run(host=CONFIG['SERVER']['HOST'], port=PORT, debug=DEBUG)
if __name__ == "__main__":
main()