Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added support for multiple printers #19

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 30 additions & 16 deletions brother_ql_web.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
This is a web service to print labels on Brother QL label printers.
Expand All @@ -21,6 +22,8 @@

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)
Expand All @@ -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() """
Expand All @@ -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'])
Expand Down Expand Up @@ -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 not context['text'] or context['text'] is None:
return_dict['message'] = 'Please provide the text for the label'
return return_dict

if context['text'] is None:
return_dict['error'] = 'Please provide the text for the label'
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)
Expand All @@ -193,13 +202,21 @@ def print_text():
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'])
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
Expand All @@ -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
Expand All @@ -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
Expand All @@ -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))

Expand All @@ -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__":
Expand Down
11 changes: 7 additions & 4 deletions config.example.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
1 change: 1 addition & 0 deletions font_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(',')
Expand Down
20 changes: 16 additions & 4 deletions views/labeldesigner.jinja2
Original file line number Diff line number Diff line change
Expand Up @@ -110,12 +110,24 @@
<label for="labelText">Label Text:</label>
<textarea rows="7" id="labelText" class="form-control" onChange="preview()" onInput="preview()"></textarea>
</fieldset>
</div>
</div>
<div class="col-md-4">
<fieldset class="form-group">
<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>
Expand All @@ -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(),
Expand All @@ -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()
}
}

Expand Down