Added support for multiple printers

Fixed runtime errors (on osx)
This commit is contained in:
Joris Reijrink 2019-03-07 09:56:56 +01:00
parent 0a2cf12c39
commit 9962289dd1
4 changed files with 54 additions and 24 deletions

View File

@ -1,4 +1,5 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This is a web service to print labels on Brother QL label printers.
@ -21,6 +22,8 @@ logger = logging.getLogger(__name__)
LABEL_SIZES = [ (name, label_type_specs[name]['name']) for name in label_sizes]
PRINTERS = {}
try:
with open('config.json') as fh:
CONFIG = json.load(fh)
@ -45,7 +48,8 @@ def labeldesigner():
'fonts': FONTS,
'label_sizes': LABEL_SIZES,
'website': CONFIG['WEBSITE'],
'label': CONFIG['LABEL']}
'label': CONFIG['LABEL'],
'printers': PRINTERS }
def get_label_context(request):
""" might raise LookupError() """
@ -69,6 +73,7 @@ def get_label_context(request):
'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.,
'printer_name': d.get('printer_name', None),
}
context['margin_top'] = int(context['font_size']*context['margin_top'])
context['margin_bottom'] = int(context['font_size']*context['margin_bottom'])
@ -179,11 +184,15 @@ def print_text():
try:
context = get_label_context(request)
except LookupError as e:
return_dict['error'] = e.msg
return_dict['message'] = e.msg
return return_dict
if context['text'] is None:
return_dict['error'] = 'Please provide the text for the label'
if not context['text'] or context['text'] is None:
return_dict['message'] = 'Please provide the text for the label'
return return_dict
if not context['printer_name'] or context['printer_name'] is None:
return_dict['message'] = 'Please select a printer'
return return_dict
im = create_label_im(**context)
@ -194,12 +203,20 @@ def print_text():
elif context['kind'] in (ROUND_DIE_CUT_LABEL, DIE_CUT_LABEL):
rotate = 'auto'
qlr = BrotherQLRaster(CONFIG['PRINTER']['MODEL'])
qlr = BrotherQLRaster(PRINTERS[context['printer_name']]["MODEL"])
create_label(qlr, im, context['label_size'], threshold=context['threshold'], cut=True, rotate=rotate)
try:
selected_backend = guess_backend(PRINTERS[context['printer_name']]["LOCATION"])
except Exception as e:
return_dict['message'] = str(e)
return return_dict
BACKEND_CLASS = backend_factory(selected_backend)['backend_class']
if not DEBUG:
try:
be = BACKEND_CLASS(CONFIG['PRINTER']['PRINTER'])
be = BACKEND_CLASS(PRINTERS[context['printer_name']]["LOCATION"])
be.write(qlr.data)
be.dispose()
del be
@ -219,13 +236,13 @@ def main():
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('--default-orientation', default=False, choices=('standard', 'rotated'), help='Label orientation, defaults to "standard". To turn your text by 90 degrees, 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
CONFIG['PRINTERS']['PRINTER'] = args.printer
if args.port:
PORT = args.port
@ -243,7 +260,7 @@ def main():
DEBUG = False
if args.model:
CONFIG['PRINTER']['MODEL'] = args.model
CONFIG['PRINTERS']['MODEL'] = args.model
if args.default_label_size:
CONFIG['LABEL']['DEFAULT_SIZE'] = args.default_label_size
@ -259,12 +276,6 @@ def main():
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))
@ -290,6 +301,9 @@ def main():
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']))
for printer in CONFIG['PRINTERS']:
PRINTERS[printer["NAME"]] = printer
run(host=CONFIG['SERVER']['HOST'], port=PORT, debug=DEBUG)
if __name__ == "__main__":

View File

@ -5,10 +5,13 @@
"LOGLEVEL": "WARNING",
"ADDITIONAL_FONT_FOLDER": false
},
"PRINTER": {
"MODEL": "QL-500",
"PRINTER": "file:///dev/usb/lp1"
},
"PRINTERS": [
{
"NAME": "Labelprinter",
"MODEL": "QL-500",
"LOCATION": "file:///dev/usb/lp1"
}
],
"LABEL": {
"DEFAULT_SIZE": "62",
"DEFAULT_ORIENTATION": "standard",

View File

@ -20,6 +20,7 @@ def get_fonts(folder=None):
if not line: continue
if 'otf' not in line and 'ttf' not in line: continue
parts = line.split(':')
if len(parts) < 3: continue
path = parts[0]
families = parts[1].strip().split(',')
styles = parts[2].split('=')[1].split(',')

View File

@ -116,6 +116,18 @@
<label for="previewImg">Label Preview:</label><br />
<img id="previewImg" style="border: 1px solid #444; max-height: 350px; width: auto; max-width: 100%; margin-bottom: 10px;"/>
<p>Printed size w/o margins: <span id="labelWidth">?</span> cm x <span id="labelHeight">?</span> cm</p>
<div {% if printers|length == 1 %} hidden {% endif %}>
<label for="printer">Printer:</label>
<select class="form-control" id="printer">
<option value="" disabled {% if printers|length > 1 %} selected {% endif %} > -- select a printer -- </option>
{% for printer in printers %}
<option value="{{printer}}" {% if printers|length == 1 %} selected {% endif %} >{{printer}}</option>
{% endfor %}
</select>
<br/>
</div>
<button id="printButton" type="button" class="btn btn-primary btn-block btn-lg" onClick="print()">
<span class="glyphicon glyphicon-print" aria-hidden="true"></span> Print
</button>
@ -136,9 +148,8 @@
var text = $('#labelText');
function formData() {
//var text = $('#labelText').val().replace(/\n/g, "%0A");
var text = $('#labelText').val();
if (text == '') text = ' ';
return {
text: text,
font_family: $('#fontFamily option:selected').text(),
@ -149,7 +160,8 @@ function formData() {
margin_top: $('#marginTop').val(),
margin_bottom: $('#marginBottom').val(),
margin_left: $('#marginLeft').val(),
margin_right: $('#marginRight').val()
margin_right: $('#marginRight').val(),
printer_name: $('#printer option:selected').val()
}
}