def print_task(printer, label): selected_backend = guess_backend(printer.connection) BACKEND_CLASS = backend_factory(selected_backend)['backend_class'] image = img_label(label) # from brother_ql qlr = BrotherQLRaster(printer.model) create_label(qlr, image, printer.width, threshold=70, cut=True, dither=False, compress=False, red=False) try: be = BACKEND_CLASS(printer.connection) be.write(qlr.data) be.dispose() del be except Exception as e: raise NameError(str(e)) return True
def __init__(self, dev, instructions_data, backend='linux_kernel'): be_cls = backend_factory(backend)['backend_class'] self.be = be_cls(dev) self.sleep_time = 0.0 self.sleep_before_read = 0.0 self.continue_reading_for = 3.0 self.start = time.time() self.interactive = False self.merge_specific_instructions = True if type(instructions_data) in (str, ): with open(instructions_data, 'rb') as f: self.instructions_data = f.read() elif type(instructions_data) in (bytes, ): self.instructions_data = instructions_data else: raise NotImplementedError( 'Only filename or bytes supported for instructions_data argument' ) response = self.be.read() if response: logger.warning( 'Received response before sending instructions: {}'.format( hex_format(response)))
def main(): """ Initializes the webserver :return: """ global DEBUG, MODEL, BACKEND_CLASS, BACKEND_STRING_DESCR import argparse parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--host', default='127.0.0.1', help='The IP the webserver should bind to. Use 0.0.0.0 for all') parser.add_argument('--port', default=8013, help='The port the webserver should start on') parser.add_argument('--debug', action='store_true', default=False, help='Activate flask debugging support') parser.add_argument('--model', default='QL-500', choices=models, help='The model of your printer (default: QL-500)') parser.add_argument('printer', help='String descriptor for the printer to use (like tcp://192.168.0.23:9100 or ' 'file:///dev/usb/lp0)') args = parser.parse_args() DEBUG = args.debug MODEL = args.model try: selected_backend = guess_backend(args.printer) BACKEND_CLASS = backend_factory(selected_backend)['backend_class'] BACKEND_STRING_DESCR = args.printer except: parser.error("Couldn't guess the backend to use from the printer string descriptor") app.run(host=args.host, port=args.port, debug=DEBUG)
def discover(backend_identifier='linux_kernel'): be = backend_factory(backend_identifier) list_available_devices = be['list_available_devices'] BrotherQLBackend = be['backend_class'] available_devices = list_available_devices() return available_devices
def __init__(self, path: str, serial: str, check_period: int = 5): self.path = path self.serial = serial self.backend_cls = backend_factory("linux_kernel")['backend_class'] self.backend = self.backend_cls(self.path) self.model: Optional[str] = None self.scheduler = EventLoopScheduler() self.status: Optional[Status] = None self.label_width: Optional[int] = None self.periodic = self.scheduler.schedule_periodic(timedelta(seconds=check_period), self._get_status)
def detect_printers() -> Dict[str, str]: info = {} accessor = backend_factory("linux_kernel") devices = accessor['list_available_devices']() for device in devices: identifier = device['identifier'] result = try_get_serial(identifier) info[result] = identifier return info
def main(): global DEBUG, FONTS, DEFAULT_FONT, MODEL, BACKEND_CLASS, BACKEND_STRING_DESCR, DEFAULT_ORIENTATION, DEFAULT_LABEL_SIZE import argparse parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--port', default=8013) parser.add_argument('--loglevel', type=lambda x: getattr(logging, x.upper()), default='WARNING') parser.add_argument('--font-folder', help='folder for additional .ttf/.otf fonts') parser.add_argument('--default-label-size', default="62", help='Label size inserted in your printer. Defaults to 62.') parser.add_argument('--default-orientation', default="standard", choices=('standard', 'rotated'), help='Label orientation, defaults to "standard". To turn your text by 90°, state "rotated".') parser.add_argument('--model', default='QL-500', choices=models, help='The model of your printer (default: QL-500)') parser.add_argument('printer', help='String descriptor for the printer to use (like tcp://192.168.0.23:9100 or file:///dev/usb/lp0)') args = parser.parse_args() DEBUG = args.loglevel == logging.DEBUG logging.basicConfig(level=args.loglevel) try: selected_backend = guess_backend(args.printer) except: parser.error("Couln't guess the backend to use from the printer string descriptor") BACKEND_CLASS = backend_factory(selected_backend)['backend_class'] BACKEND_STRING_DESCR = args.printer MODEL = args.model if args.default_label_size not in label_sizes: parser.error("Invalid --default-label-size. Please choose on of the following:\n:" + " ".join(label_sizes)) DEFAULT_LABEL_SIZE = args.default_label_size DEFAULT_ORIENTATION = args.default_orientation FONTS = get_fonts() if args.font_folder: FONTS.update(get_fonts(args.font_folder)) for font in DEFAULT_FONTS: try: FONTS[font['family']][font['style']] DEFAULT_FONT = font logger.debug("Selected the following default font: {}".format(font)) break except: pass if DEFAULT_FONT is None: sys.stderr.write('Could not find any of the default fonts') sys.exit() run(host='', port=args.port, debug=DEBUG)
def __init__(self, dev, instructions_data, backend='linux_kernel'): be_cls = backend_factory(backend)['backend_class'] self.be = be_cls(dev) self.sleep_time = 0.0 self.sleep_before_read = 0.0 self.continue_reading_for = 3.0 self.start = time.time() self.interactive = False self.merge_specific_instructions = True if type(instructions_data) in (str,): with open(instructions_data, 'rb') as f: self.instructions_data = f.read() elif type(instructions_data) in (bytes,): self.instructions_data = instructions_data else: raise NotImplementedError('Only filename or bytes supported for instructions_data argument') response = self.be.read() if response: logger.warning('Received response before sending instructions: {}'.format(hex_format(response)))
def main(): global DEBUG, FONTS, DEFAULT_FONT, MODEL, BACKEND_CLASS, BACKEND_STRING_DESCR import argparse parser = argparse.ArgumentParser() parser.add_argument('--port', default=8013) parser.add_argument('--loglevel', type=lambda x: getattr(logging, x.upper()), default='WARNING') parser.add_argument('--font-folder', help='folder for additional .ttf/.otf fonts') parser.add_argument('--model', default='QL-500', choices=models, help='The model of your printer (default: QL-500)') parser.add_argument('printer', help='String descriptor for the printer to use (like tcp://192.168.0.23:9100 or file:///dev/usb/lp0)') args = parser.parse_args() DEBUG = args.loglevel == logging.DEBUG logging.basicConfig(level=args.loglevel) try: selected_backend = guess_backend(args.printer) except: parser.error("Couln't guess the backend to use from the printer string descriptor") BACKEND_CLASS = backend_factory(selected_backend)['backend_class'] BACKEND_STRING_DESCR = args.printer MODEL = args.model FONTS = get_fonts() if args.font_folder: FONTS.update(get_fonts(args.font_folder)) for font in DEFAULT_FONTS: try: FONTS[font['family']][font['style']] DEFAULT_FONT = font logger.debug("Selected the following default font: {}".format(font)) break except: pass if DEFAULT_FONT is None: sys.stderr.write('Could not find any of the default fonts') sys.exit() run(host='', port=args.port, debug=args.loglevel==logging.DEBUG)
def prt(self): print(label_type_specs[self.size]) if label_type_specs[self.size]['kind'] == ENDLESS_LABEL: rot = 0 if not self.rotated else 90 else: rot = 'auto' if label_type_specs[self.size]['kind'] != 2: label_type_specs[ self.size]['feed_margin'] = config['label']['feed_margin'] qlr = BrotherQLRaster(config['printer']['model']) if config['printer']['model'] in cuttingsupport: logger.debug('Printer is capable of automatic cutting.') cutting = True else: logger.debug('Printer is not capable of automatic cutting.') cutting = False create_label(qlr, self.image, self.size, threshold=30, cut=cutting, rotate=rot) try: backend_class = backend_factory(backend)['backend_class'] be = backend_class(config['printer']['device']) pprint(vars(be)) be.write(qlr.data) be.dispose() del be # TODO better feedback from printer return "alert-success", "<b>Success:</b>Label printed" except Exception as e: logger.warning("unable tp print") logger.warning(e) return "danger", "unable to print"
def label_print(): global DEBUG, FONTS, DEFAULT_FONT, MODEL, BACKEND_CLASS, BACKEND_STRING_DESCR, DEFAULT_ORIENTATION, DEFAULT_LABEL_SIZE printer = "tcp://192.168.11.106:9100" model = "QL-720NW" # Default label size is "62x100" (DK-11202) which use "rotated" in orientation. # If label size in "62x29" (DK-11209), use "standard" in orientation. default_label_size = "62x100" default_orientation = "rotated" font_folder = "./static/fonts" selected_backend = guess_backend(printer) BACKEND_CLASS = backend_factory(selected_backend)['backend_class'] BACKEND_STRING_DESCR = printer MODEL = model #if default_label_size not in label_sizes: #parser.error("Invalid --default-label-size. Please choose on of the following:\n:" + " ".join(label_sizes)) DEFAULT_LABEL_SIZE = default_label_size DEFAULT_ORIENTATION = default_orientation FONTS = get_fonts() if font_folder: FONTS.update(get_fonts(font_folder))
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)
def main(): global DEBUG, BACKEND_CLASS, CONFIG, IMG_DIR, FILE_NAMES 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( '--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() IMG_DIR = "./img/" update_files() 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 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)) run(host=CONFIG['SERVER']['HOST'], port=PORT, debug=DEBUG)
def main(): global DEBUG, FONTS, BACKEND_CLASS, CONFIG parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--port', default=False) parser.add_argument('--loglevel', type=str, default=False) parser.add_argument('--font-folder', default=False, help='folder for additional .ttf/.otf fonts') parser.add_argument('--system-fonts', default=False, help='Include fonts installed in OS.') 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-image-mode', default=False, choices=('black_and_white', 'grayscale'), help= 'Image mode, defaults to "grayscale". To print in black and white, state "black_and_white".' ) 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.loglevel: LOGLEVEL_STRING = args.loglevel.upper() LOGLEVEL = getattr(logging, LOGLEVEL_STRING) else: LOGLEVEL_STRING = CONFIG['SERVER']['LOGLEVEL'].upper() LOGLEVEL = getattr(logging, LOGLEVEL_STRING) if LOGLEVEL_STRING == 'DEBUG': DEBUG = True else: DEBUG = False logging.basicConfig(level=LOGLEVEL) logger.info("Log Level set to {} ({}). DEBUG={}".format( LOGLEVEL, LOGLEVEL_STRING, DEBUG)) if args.printer: CONFIG['PRINTER']['PRINTER'] = args.printer if args.port: PORT = args.port else: PORT = CONFIG['SERVER']['PORT'] 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.default_image_mode: CONFIG['LABEL']['DEFAULT_IMAGE_MODE'] = args.default_image_mode if args.font_folder: ADDITIONAL_FONT_FOLDER = args.font_folder else: ADDITIONAL_FONT_FOLDER = CONFIG['SERVER']['ADDITIONAL_FONT_FOLDER'] if args.system_fonts: SYSTEM_FONTS = True else: SYSTEM_FONTS = CONFIG['SERVER']['INCLUDE_SYSTEM_FONTS'] 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 = fonts.Fonts() if SYSTEM_FONTS: FONTS.scan_global_fonts() else: FONTS.scan_fonts_folder('./fonts') if ADDITIONAL_FONT_FOLDER: FONTS.scan_fonts_folder(ADDITIONAL_FONT_FOLDER) if not FONTS.fonts_available(): logger.error( "Not a single font was found on your system. Please install some or use the \"--font-folder\" argument." ) sys.exit(2) DEFAULT_FONT = CONFIG['LABEL']['DEFAULT_FONT'] if not (DEFAULT_FONT['family'] in FONTS.fonts.keys() and DEFAULT_FONT['style'] in FONTS.fonts[DEFAULT_FONT['family']].keys()): family = random.choice(list(FONTS.fonts.keys())) style = random.choice(list(FONTS.fonts[family].keys())) CONFIG['LABEL']['DEFAULT_FONT'] = {'family': family, 'style': style} logger.warn( "Could not find the default font. A random font was selected: {family} ({style})" .format(**CONFIG['LABEL']['DEFAULT_FONT'])) # initialize bootstrap app.config['BOOTSTRAP_SERVE_LOCAL'] = True bootstrap = Bootstrap(app) app.run(host=CONFIG['SERVER']['HOST'], port=PORT, debug=DEBUG)
def run(self): inputTwitter = window.rootObject().findChild(QObject, 'inputTwitter') inputTwitter.select(0,0) if inputTwitter.property('text') == "@twitter" or len(inputTwitter.property("text")) < 1: inputTwitter.setProperty("visible", False) inputName = window.rootObject().findChild(QObject, 'inputName') inputName.select(0,0) checkboxSelected = True#window.rootObject().findChild(QObject, 'checkboxSelected').property('visible') label = window.rootObject().findChild(QObject, 'textLos') ticket = '' if checkboxSelected: ticket = self.get_ticket_number() label.setProperty("text", "Los #%s" % ticket) #label.setProperty("visible", True) inputName.setProperty('focus', False) inputTwitter.setProperty('focus', False) badge = window.rootObject().findChild(QObject, 'badge') image = QPixmap.grabWidget(window, badge.x(), badge.y(), badge.width(), badge.height()) window.rootObject().findChild(QObject, "animateNameBadgeOff").start() self.app.processEvents(QEventLoop.AllEvents, 2000) bytes = QByteArray() buffer = QBuffer(bytes) buffer.open(QIODevice.WriteOnly) image.save(buffer, "PNG") buffer.close() img = PIL.Image.open(BytesIO(bytes.data())) img.thumbnail((2000, 413)) img = img.rotate(90) print (img.size) qlr = BrotherQLRaster(config['type']) qlr.exception_on_warning=True create_label(qlr, img, '38') selected_backend = 'linux_kernel' be = backend_factory(selected_backend) list_available_devices = be['list_available_devices'] BrotherQLBackend = be['backend_class'] printer = BrotherQLBackend(config['device']) printer.write(qlr.data) r = ">" while r: r = printer.read() print (r) print ("\nDone printing!") c = self.conn.cursor() c.execute(""" INSERT INTO badges (created, name, twitter, ticket) VALUES (datetime('now'),?,?,?) """, (inputName.property('text'), inputTwitter.property('text'), ticket)) self.conn.commit() c.close() QTimer.singleShot(2000, lambda: self.reset_ui())
def main(): parser = argparse.ArgumentParser() parser.add_argument('--backend', choices=available_backends, help='Forces the use of a specific backend') parser.add_argument( '--list-printers', action='store_true', help='List the devices available with the selected --backend') parser.add_argument('--debug', action='store_true', help='Enable debugging output') parser.add_argument( 'instruction_file', nargs='?', help='file containing the instructions to be sent to the printer') parser.add_argument( 'device', metavar='DEVICE_STRING_DESCRIPTOR', nargs='?', help= 'String descriptor for specific device. If not specified, select first detected device' ) args = parser.parse_args() if args.list_printers and not args.backend: parser.error( 'Please specify the backend in order to list available devices.') if not args.list_printers and not args.instruction_file: parser.error("the following arguments are required: instruction_file") if args.instruction_file == '-': try: content = sys.stdin.buffer.read() except AttributeError: content = sys.stdin.read() else: with open(args.instruction_file, 'rb') as f: content = f.read() level = logging.DEBUG if args.debug else logging.WARNING logging.basicConfig(level=level) if args.backend == 'network': logger.warning( "The network backend doesn't supply any 'readback' functionality. No status reports will be received." ) selected_backend = None if args.backend: selected_backend = args.backend else: try: selected_backend = guess_backend(args.device) except: logger.info( "No backend stated. Selecting the default linux_kernel backend." ) selected_backend = 'linux_kernel' be = backend_factory(selected_backend) list_available_devices = be['list_available_devices'] BrotherQLBackend = be['backend_class'] if args.list_printers: for printer in list_available_devices(): print(printer['string_descr']) sys.exit(0) string_descr = None if not args.device: "We need to search for available devices and select the first." ad = list_available_devices() if not ad: sys.exit("No printer found") string_descr = ad[0]['string_descr'] print("Selecting first device %s" % string_descr) else: "A string descriptor for the device was given, let's use it." string_descr = args.device printer = BrotherQLBackend(string_descr) start = time.time() logger.info('Sending instructions to the printer. Total: %d bytes.', len(content)) printer.write(content) if selected_backend == 'network': """ No need to wait for completion. The network backend doesn't support readback. """ return printing_completed = False waiting_to_receive = False while time.time() - start < 10: data = printer.read() if not data: time.sleep(0.005) continue try: result = interpret_response(data) except ValueError: logger.error("TIME %.3f - Couln't understand response: %s", time.time() - start, data) continue logger.debug('TIME %.3f - result: %s', time.time() - start, result) if result['errors']: logger.error('Errors occured: %s', result['errors']) if result['status_type'] == 'Printing completed': printing_completed = True if result['status_type'] == 'Phase change' and result[ 'phase_type'] == 'Waiting to receive': waiting_to_receive = True if printing_completed and waiting_to_receive: break if not (printing_completed and waiting_to_receive): logger.warning('Printing potentially not successful?')
import glob from PIL import Image, ImageDraw, ImageFont from elaphe import barcode from brother_ql import BrotherQLRaster, create_label from brother_ql.backends import backend_factory TESTING = False if not TESTING: # Setup label printer be = backend_factory("linux_kernel") BrotherQLBackend = be['backend_class'] devices = glob.glob('/dev/usb/lp*') if not devices: raise RuntimeError('Please plug in the label printer and rerun this script') printer = BrotherQLBackend(devices[0]) for id in range(1,11): text = '{:06}'.format(id) # Create blank image img = Image.new('L', (696, 128), 255) # Add DataMatrix barcode code = barcode('datamatrix', text, options={'rows': 16, 'columns': 16}, margins=10) # type: Image img.paste(code.rotate(90).resize((128,128)), (0,0)) # Add ID 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['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 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) 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(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(PRINTERS[context['printer_name']]["LOCATION"]) 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 send(instructions, printer_identifier=None, backend_identifier=None, blocking=True): """ Send instruction bytes to a printer. :param bytes instructions: The instructions to be sent to the printer. :param str printer_identifier: Identifier for the printer. :param str backend_identifier: Can enforce the use of a specific backend. :param bool blocking: Indicates whether the function call should block while waiting for the completion of the printing. """ selected_backend = None if backend_identifier: selected_backend = backend_identifier else: try: selected_backend = guess_backend(printer_identifier) except: logger.info("No backend stated. Selecting the default linux_kernel backend.") selected_backend = 'linux_kernel' be = backend_factory(selected_backend) list_available_devices = be['list_available_devices'] BrotherQLBackend = be['backend_class'] printer = BrotherQLBackend(printer_identifier) start = time.time() logger.info('Sending instructions to the printer. Total: %d bytes.', len(instructions)) printer.write(instructions) if not blocking: return if selected_backend == 'network': """ No need to wait for completion. The network backend doesn't support readback. """ return printing_completed = False waiting_to_receive = False while time.time() - start < 10: data = printer.read() if not data: time.sleep(0.005) continue try: result = interpret_response(data) except ValueError: logger.error("TIME %.3f - Couln't understand response: %s", time.time()-start, data) continue logger.debug('TIME %.3f - result: %s', time.time()-start, result) if result['errors']: logger.error('Errors occured: %s', result['errors']) if result['status_type'] == 'Printing completed': printing_completed = True if result['status_type'] == 'Phase change' and result['phase_type'] == 'Waiting to receive': waiting_to_receive = True if printing_completed and waiting_to_receive: break if not printing_completed: logger.warning("'printing completed' status not received.") if not waiting_to_receive: logger.warning("'waiting to receive' status not received.") if (not printing_completed) or (not waiting_to_receive): logger.warning('Printing potentially not successful?') if printing_completed and waiting_to_receive: logger.info("Printing was successful. Waiting for the next job.")
def main(): global DEBUG, 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', action="append", help='Specify additional folders for additional .ttf/.otf fonts.') parser.add_argument('--no-system-fonts', action="store_true", help='Do not search system folders for 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 ADDITIONAL_FONT_FOLDERS = (args.font_folder or []) + ( CONFIG['SERVER']['ADDITIONAL_FONT_FOLDERS'] or []) NO_SYSTEM_FONTS = args.no_system_fonts or CONFIG['SERVER'][ 'NO_SYSTEM_FONTS'] 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)) if NO_SYSTEM_FONTS: fc = fontconfig.Config.create() else: fc = fontconfig.Config.get_current() if ADDITIONAL_FONT_FOLDERS: for folder in ADDITIONAL_FONT_FOLDERS: fc.app_font_add_dir(folder) props = fontconfig.PROP.FILE, fontconfig.PROP.FAMILY, fontconfig.PROP.STYLE CONFIG['FONTS'] = [] for font in fc.font_list(fontconfig.Pattern.create(), props): CONFIG['FONTS'].append(tuple(font.get(prop, 0)[0] for prop in props)) CONFIG['FONTS'].sort(key=lambda font: font[1:]) if not CONFIG['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 default_font in CONFIG['LABEL'].get('DEFAULT_FONTS', ()): for i, font in enumerate(CONFIG['FONTS']): if default_font['family'] == font[1] and default_font[ 'style'] == font[2]: CONFIG['LABEL']['DEFAULT_FONT'] = i logger.debug( "Selected the following default font: {}".format(font)) break if 'DEFAULT_FONT' in CONFIG['LABEL']: break else: sys.stderr.write( 'Could not find any of the default fonts. Choosing a random one.\n' ) CONFIG['LABEL']['DEFAULT_FONT'] = random.randint( 0, len(CONFIG['FONTS'])) sys.stderr.write('The default font is now set to: {1} ({2})\n'.format( *CONFIG['FONTS'][CONFIG['LABEL']['DEFAULT_FONT']])) run(host=CONFIG['SERVER']['HOST'], port=PORT, debug=DEBUG)
def main(): parser = argparse.ArgumentParser() parser.add_argument("--backend", choices=available_backends, help="Forces the use of a specific backend") parser.add_argument( "--list-printers", action="store_true", help="List the devices available with the selected --backend" ) parser.add_argument("--debug", action="store_true", help="Enable debugging output") parser.add_argument( "instruction_file", nargs="?", help="file containing the instructions to be sent to the printer" ) parser.add_argument( "device", metavar="DEVICE_STRING_DESCRIPTOR", nargs="?", help="String descriptor for specific device. If not specified, select first detected device", ) args = parser.parse_args() if args.list_printers and not args.backend: parser.error("Please specify the backend in order to list available devices.") if not args.list_printers and not args.instruction_file: parser.error("the following arguments are required: instruction_file") level = logging.DEBUG if args.debug else logging.WARNING logging.basicConfig(level=level) if args.backend == "network": logger.warning( "The network backend doesn't supply any 'readback' functionality. No status reports will be received." ) selected_backend = None if args.backend: selected_backend = args.backend else: try: selected_backend = guess_backend(args.device) except: logger.info("No backend stated. Selecting the default linux_kernel backend.") selected_backend = "linux_kernel" be = backend_factory(selected_backend) list_available_devices = be["list_available_devices"] BrotherQLBackend = be["backend_class"] if args.list_printers: for printer in list_available_devices(): print(printer["string_descr"]) sys.exit(0) string_descr = None if not args.device: "We need to search for available devices and select the first." ad = list_available_devices() if not ad: sys.exit("No printer found") string_descr = ad[0]["string_descr"] print("Selecting first device %s" % string_descr) else: "A string descriptor for the device was given, let's use it." string_descr = args.device printer = BrotherQLBackend(string_descr) start = time.time() with open(args.instruction_file, "rb") as f: content = f.read() logger.info("Sending instructions to the printer. Total: %d bytes.", len(content)) printer.write(content) if selected_backend == "network": """ No need to wait for completion. The network backend doesn't support readback. """ return printing_completed = False waiting_to_receive = False while time.time() - start < 10: data = printer.read() if not data: time.sleep(0.005) continue try: result = interpret_response(data) except ValueError: logger.error("TIME %.3f - Couln't understand response: %s", time.time() - start, data) continue logger.debug("TIME %.3f - result: %s", time.time() - start, result) if result["errors"]: logger.error("Errors occured: %s", result["errors"]) if result["status_type"] == "Printing completed": printing_completed = True if result["status_type"] == "Phase change" and result["phase_type"] == "Waiting to receive": waiting_to_receive = True if printing_completed and waiting_to_receive: break if not (printing_completed and waiting_to_receive): logger.warning("Printing potentially not successful?")
titleImage.save("tmp4.bmp") newImage.paste(titleImage, (0, 0)) newImage.paste(img, (0, int(y // 4 + 1))) newImage.save("tmp1.bmp") newImage.paste(textImage, (x, int(y // 4 + 1))) newImage.save("tmp3.bmp") # 29x90 Codes 306x 991 qlr = brother_ql.BrotherQLRaster('QL-700') qlr.exception_on_warning = True brother_ql.create_label(qlr, newImage, '62') fo = open(mypath2, 'wb') fo.write(qlr.data) fo.close() be = backend_factory('pyusb') list_available_devices = be['list_available_devices'] BrotherQLBackend = be['backend_class'] ad = list_available_devices() for printer in ad: print("HERE") print(ad) print(printer['identifier']) string_descr = ad[0]['identifier'] print("Selecting first device %s" % string_descr) printer = BrotherQLBackend(string_descr) printer.write(qlr.data)
def print_text(**data): global DEBUG, FONTS, DEFAULT_FONT, MODEL, BACKEND_CLASS, BACKEND_STRING_DESCR, DEFAULT_ORIENTATION, DEFAULT_LABEL_SIZE BACKEND_STRING_DESCR = data['printer_uri'] # "tcp://192.168.0.10:9100" font_folder = "./static/fonts" selected_backend = guess_backend(BACKEND_STRING_DESCR) BACKEND_CLASS = backend_factory(selected_backend)['backend_class'] MODEL = data['printer_model'] # "QL-720NW" DEFAULT_LABEL_SIZE = data['label_size'] # "62x100" DEFAULT_ORIENTATION = data['orientation'] # "rotated" FONTS = get_fonts() if font_folder: FONTS.update(get_fonts(font_folder)) status = False try: context = get_label_context(data['first_name'], data['last_name'], data['company'], data['label_size']) except LookupError as e: return status if context['name'] is None: return status if context['company'] is None: context['company'] = '' if context['last_name'] is None: context['name'] = context['first_name'] context['event_name'] = data['event_name'] context['logo'] = data['logo'] context['label_tpl'] = data['label_tpl'] context['ticket_type'] = data['ticket_type'] im = eval('create_label_im_' + data['label_size'])(**context) if data['debug']: data['image'] = im try: im.save(settings.MEDIA_ROOT + '/cache/label-%s_%s.png' % (data['first_name'], data['last_name'])) except FileNotFoundError: os.mkdir(settings.MEDIA_ROOT + '/cache') im.save(settings.MEDIA_ROOT + '/cache/label-%s_%s.png' % (data['first_name'], data['last_name'])) else: qlr = BrotherQLRaster(MODEL) rotate = 0 if data['orientation'] == 'standard' else 90 if context['label_size'] == '62x29': rotate = 0 create_label(qlr, im, context['label_size'], threshold=context['threshold'], cut=True, rotate=rotate) try: be = BACKEND_CLASS(BACKEND_STRING_DESCR) be.write(qlr.data) be.dispose() del be except Exception as e: return status status = True return status
def send(instructions, printer_identifier=None, backend_identifier=None, blocking=True): """ Send instruction bytes to a printer. :param bytes instructions: The instructions to be sent to the printer. :param str printer_identifier: Identifier for the printer. :param str backend_identifier: Can enforce the use of a specific backend. :param bool blocking: Indicates whether the function call should block while waiting for the completion of the printing. """ status = { 'instructions_sent': True, # The instructions were sent to the printer. 'outcome': 'unknown', # String description of the outcome of the sending operation like: 'unknown', 'sent', 'printed', 'error' 'printer_state': None, # If the selected backend supports reading back the printer state, this key will contain it. 'did_print': False, # If True, a print was produced. It defaults to False if the outcome is uncertain (due to a backend without read-back capability). 'ready_for_next_job': False, # If True, the printer is ready to receive the next instructions. It defaults to False if the state is unknown. } selected_backend = None if backend_identifier: selected_backend = backend_identifier else: try: selected_backend = guess_backend(printer_identifier) except: logger.info( "No backend stated. Selecting the default linux_kernel backend." ) selected_backend = 'linux_kernel' be = backend_factory(selected_backend) list_available_devices = be['list_available_devices'] BrotherQLBackend = be['backend_class'] printer = BrotherQLBackend(printer_identifier) start = time.time() logger.info('Sending instructions to the printer. Total: %d bytes.', len(instructions)) printer.write(instructions) status['outcome'] = 'sent' if not blocking: return status if selected_backend == 'network': """ No need to wait for completion. The network backend doesn't support readback. """ return status while time.time() - start < 10: data = printer.read() if not data: time.sleep(0.005) continue try: result = interpret_response(data) except ValueError: logger.error("TIME %.3f - Couln't understand response: %s", time.time() - start, data) continue status['printer_state'] = result logger.debug('TIME %.3f - result: %s', time.time() - start, result) if result['errors']: logger.error('Errors occured: %s', result['errors']) status['outcome'] = 'error' break if result['status_type'] == 'Printing completed': status['did_print'] = True status['outcome'] = 'printed' if result['status_type'] == 'Phase change' and result[ 'phase_type'] == 'Waiting to receive': status['ready_for_next_job'] = True if status['did_print'] and status['ready_for_next_job']: break if not status['did_print']: logger.warning("'printing completed' status not received.") if not status['ready_for_next_job']: logger.warning("'waiting to receive' status not received.") if (not status['did_print']) or (not status['ready_for_next_job']): logger.warning('Printing potentially not successful?') if status['did_print'] and status['ready_for_next_job']: logger.info("Printing was successful. Waiting for the next job.") return status
def print_text(**data): global DEBUG, FONTS, DEFAULT_FONT, MODEL, BACKEND_CLASS, BACKEND_STRING_DESCR, DEFAULT_ORIENTATION, DEFAULT_LABEL_SIZE BACKEND_STRING_DESCR = data["printer_uri"] # "tcp://192.168.0.10:9100" font_folder = "./static/fonts" selected_backend = guess_backend(BACKEND_STRING_DESCR) BACKEND_CLASS = backend_factory(selected_backend)["backend_class"] MODEL = data["printer_model"] # "QL-720NW" DEFAULT_LABEL_SIZE = data["label_size"] # "62x100" DEFAULT_ORIENTATION = data["orientation"] # "rotated" FONTS = get_fonts() if font_folder: FONTS.update(get_fonts(font_folder)) status = False try: context = get_label_context( data["first_name"], data["last_name"], data["company"], data["label_size"] ) except LookupError as e: return status if context["name"] is None: return status if context["company"] is None: context["company"] = "" if context["last_name"] is None: context["name"] = context["first_name"] context["event_name"] = data["event_name"] context["logo"] = data["logo"] context["label_tpl"] = data["label_tpl"] context["ticket_type"] = data["ticket_type"] im = eval("create_label_im_" + data["label_size"])(**context) if data["debug"]: data["image"] = im try: im.save( settings.MEDIA_ROOT + "/cache/label-%s_%s.png" % (data["first_name"], data["last_name"]) ) except FileNotFoundError: os.mkdir(settings.MEDIA_ROOT + "/cache") im.save( settings.MEDIA_ROOT + "/cache/label-%s_%s.png" % (data["first_name"], data["last_name"]) ) else: qlr = BrotherQLRaster(MODEL) rotate = 0 if data["orientation"] == "standard" else 90 if context["label_size"] == "62x29": rotate = 0 create_label( qlr, im, context["label_size"], threshold=context["threshold"], cut=True, rotate=rotate, ) try: be = BACKEND_CLASS(BACKEND_STRING_DESCR) be.write(qlr.data) be.dispose() del be except Exception as e: return status status = True return status