def svg_to_printer(svg): #config printer # lsus # lsusb -vvv -d 4b43:3538"b # sudo usermod -a -G dialout user # sudo usermod -a -G tty user # sudo usermod -a -G lp user # ls -la /dev/usb/ # escape svg tofile("svg_to_print1_debug.svg",svg) #svg = svg.decode('utf-8').encode('ascii') # todo: problem with special char are used, find othern way to do that. tofile("svg_to_print2_debug.svg",svg) png_file = svg_to_png(svg) for try_num in (1, 2, 3): try: printer = BrotherQLRaster('QL-800') printer.exception_on_warning = True instructions = convert(qlr=printer, cut=True, images=[png_file], label="62", dither=True, dpi_600=False) send(instructions=instructions, printer_identifier='usb://0x04f9:0x209b/000A9Z276036', backend_identifier='pyusb', blocking=True) except Exception as exc: print("Error printing: %s (try %d)" % (str(exc), try_num)) time.sleep(5) else: return True return False
def print_label(text, qr=None, label="54", printer_identifier="/dev/usb/lp0", template="/home/pi/printer/templates/test.png", printer="QL-810W", cut=True, red=True, dpi_600=True, rotate="0"): # create a card from the template # card = create_card(target_file=template, text=text, qr=qr, save=False) card = generate_card(target_file=template, text=text) # convert the card to raster qlr = BrotherQLRaster(printer) qlr.exception_on_warning = True # convert takes only an array images = [card] instructions = convert(qlr=qlr, images=images, label=label, cut=cut, red=red, rotate=rotate) # get the backend identifier backend_identifier = guess_backend(printer_identifier) # send the commands to the printer print("Sending instructions to print") send(instructions=instructions, printer_identifier=printer_identifier, backend_identifier=backend_identifier)
def sendToPrinter(img): backend = config['printer'][ 'backend'] # 'pyusb', 'linux_kernal', 'network' model = config['printer']['model'] # your printer model. printer = config['printer']['printer'] im = img qlr = BrotherQLRaster(model) qlr.exception_on_warning = True instructions = convert( qlr=qlr, images=[im], # Takes a list of file names or PIL objects. label=config['printer']['label'], rotate=config['printer']['rotate'], # threshold=70.0, dither=True, compress=False, red=bool(config['printer'] ['label']), # Only True if using Red/Black 62 mm label tape. # dpi_600=False, # lq=False, # True for low quality. no_cut=False) printstate = send(instructions=instructions, printer_identifier=printer, backend_identifier=backend) return (printstate['did_print'], printstate['ready_for_next_job'])
def print_img(img, model, label, device): # Setup printer qlr = BrotherQLRaster(model) qlr.exception_on_warning = True convert(qlr, [img], label) # Convert send(qlr.data, device) # Do the printing
def print_cmd(ctx, *args, **kwargs): """ Print a label of the provided IMAGE. """ backend = ctx.meta.get('BACKEND', 'pyusb') model = ctx.meta.get('MODEL') printer = ctx.meta.get('PRINTER') from brother_ql.conversion import convert from brother_ql.backends.helpers import send from brother_ql.raster import BrotherQLRaster qlr = BrotherQLRaster(model) qlr.exception_on_warning = True instructions = convert(qlr=qlr, **kwargs) send(instructions=instructions, printer_identifier=printer, backend_identifier=backend, blocking=True)
def checkin(): id = request.form.get("id") user_id = request.form.get("user_id") line1 = request.form.get("line1") line2 = request.form.get("line2") if id is not None: r = requests.post("{0}/checkin/{1}?auth={2}".format(API_URL, id, KEY)) if not r.ok: flash("Problem while updating the check-in time", "danger") icon = None if user_id is not None: photo_url = "{0}/photo/{1}?auth={2}".format(API_URL, user_id, KEY) r = requests.get(photo_url) if r.ok: icon = BytesIO() icon.write(r.content) icon.seek(0) badge = DefaultBadgeTemplate(default_font="DejaVuSans") data = { 'line1': line1, 'line2': line2, 'icon': icon, } badge.render(data, 'tmp.png', background='birthday.png') qlr = BrotherQLRaster(PRINTER["MODEL"]) qlr.exception_on_warning = True kwargs = { 'label': PRINTER['LABEL'], 'red': True, 'rotate': '90', 'images': { open('tmp.png', 'rb'), }, 'cut': True, } instructions = convert(qlr=qlr, **kwargs) send(instructions=instructions, printer_identifier=PRINTER["PRINTER"], backend_identifier=PRINTER["BACKEND"], blocking=False) flash('Printing nametag for {0}...'.format(line1), 'info') return redirect(url_for('index'))
def call_print_api(image_path: str, printer_model: str, label_type: str, printer_backend: str, printer_url: str, red: bool, low_quality: bool, high_dpi: bool, compress: bool): """ Prints an image by calling the brother_ql python API """ logger.debug(f'Printing via brother_ql library...') raster = BrotherQLRaster(printer_model) raster.exception_on_warning = True high_quality = not low_quality threshold = 70 rotate = "auto" cut = True dither = False image_paths = [image_path] logger.debug(f"Converting image {image_path} to printing instructions...") # TODO: maybe brother_ql can read PIL Image instead of files; would prevent writing files instructions = convert(qlr=raster, images=image_paths, label=label_type, cut=cut, dither=dither, compress=compress, red=red, rotate=rotate, dpi_600=high_dpi, hq=high_quality, threshold=threshold) logger.debug( f"Converted image {image_path} to printing instructions: {len(instructions)} bytes" ) blocking = True logger.debug( f"Sending printing instructions to printer '{printer_url}' via '{printer_backend}' backend..." ) status = send(instructions=instructions, printer_identifier=printer_url, backend_identifier=printer_backend, blocking=blocking) logger.debug( f"Sent printing instructions to printer '{printer_url}' via '{printer_backend}' backend: {status}" ) return status # CAVEAT: network backend does not support readback according to brother_ql internals
def printticket(): #create ticketinfo ticketinfo.set(str(time.strftime('%m%d%H%M%S') + userCIP.get()[0:11])) display_notification(notification_printticket) #generate barcode png: barcode_class = barcode.get_barcode_class('code128') finalcode = barcode_class(ticketinfo.get(), writer=ImageWriter()) fullname = finalcode.save('barcode') bardcode_img = Image.open('./barcode.png') bardcode_img = bardcode_img.resize((991, 306)) #send ocmmand to printer backend = 'linux_kernel' # 'pyusb', 'linux_kernal', 'network' model = 'QL-700' # your printer model. global printeraddress printer = printeraddress qlr = BrotherQLRaster(model) qlr.exception_on_warning = True instructions = convert( qlr=qlr, images=[bardcode_img], # Takes a list of file names or PIL objects. label='62', # Corresponding label rotate='auto', # 'Auto', '0', '90', '270' threshold=70.0, # Black and white threshold in percent. dither=False, compress=False, red=False, # Only True if using Red/Black 62 mm label tape. dpi_600=False, lq=False, # True for low quality. no_cut=False) send(instructions=instructions, printer_identifier=printer, backend_identifier=backend, blocking=True) #finalize printing return_submit()
def main(): parser = argparse.ArgumentParser() parser.add_argument('image', help='The image file to create a label from.') parser.add_argument('outfile', nargs='?', type=argparse.FileType('wb'), default=stdout, help='The file to write the instructions to. Defaults to stdout.') parser.add_argument('--model', '-m', default='QL-500', help='The printer model to use. Check available ones with `brother_ql_info list-models`.') parser.add_argument('--label-size', '-s', default='62', help='The label size (and kind) to use. Check available ones with `brother_ql_info list-label-sizes`.') parser.add_argument('--rotate', '-r', choices=('0', '90', '180', '270'), default='auto', help='Rotate the image (counterclock-wise) by this amount of degrees.') parser.add_argument('--threshold', '-t', type=float, default=70.0, help='The threshold value (in percent) to discriminate between black and white pixels.') parser.add_argument('--dither', '-d', action='store_true', help='Enable dithering when converting the image to b/w. If set, --threshold is meaningless.') parser.add_argument('--compress', '-c', action='store_true', help='Enable compression (if available with the model). Takes more time but results in smaller file size.') parser.add_argument('--red', action='store_true', help='Create a label to be printed on black/red/white tape (only with QL-8xx series on DK-22251 labels). You must use this option when printing on black/red tape, even when not printing red.') parser.add_argument('--600dpi', action='store_true', dest='dpi_600', help='Print with 600x300 dpi available on some models. Provide your image as 600x600 dpi; perpendicular to the feeding the image will be resized to 300dpi.') parser.add_argument('--lq', action='store_false', dest='hq', help='Print with low quality (faster). Default is high quality.') parser.add_argument('--no-cut', dest='cut', action='store_false', help="Don't cut the tape after printing the label.") parser.add_argument('--loglevel', type=lambda x: getattr(logging, x), default=logging.WARNING, help='Set to DEBUG for verbose debugging output to stderr.') args = parser.parse_args() logging.basicConfig(level=args.loglevel) logging.getLogger("PIL.PngImagePlugin").setLevel(logging.WARNING) args.model = args.model.upper() try: qlr = BrotherQLRaster(args.model) except BrotherQLUnknownModel: sys.exit("Unknown model. Use the command brother_ql_info list-models to show available models.") try: label_type_specs[args.label_size] except ValueError: sys.exit("Unknown label_size. Check available sizes with the command brother_ql_info list-label-sizes") qlr.exception_on_warning = True create_label(qlr, args.image, args.label_size, threshold=args.threshold, cut=args.cut, rotate=args.rotate, dither=args.dither, compress=args.compress, red=args.red, dpi_600=args.dpi_600, hq=args.hq) args.outfile.write(qlr.data)
def main(): parser = argparse.ArgumentParser() parser.add_argument('image', help='The image file to create a label from.') parser.add_argument( 'outfile', nargs='?', type=argparse.FileType('wb'), default=stdout, help='The file to write the instructions to. Defaults to stdout.') parser.add_argument( '--model', '-m', default='QL-500', help= 'The printer model to use. Check available ones with `brother_ql_info list-models`.' ) parser.add_argument( '--label-size', '-s', default='62', help= 'The label size (and kind) to use. Check available ones with `brother_ql_info list-label-sizes`.' ) parser.add_argument( '--rotate', '-r', choices=('0', '90', '180', '270'), default='auto', help='Rotate the image (counterclock-wise) by this amount of degrees.') parser.add_argument( '--threshold', '-t', type=float, default=70.0, help= 'The threshold value (in percent) to discriminate between black and white pixels.' ) parser.add_argument('--no-cut', dest='cut', action='store_false', help="Don't cut the tape after printing the label.") parser.add_argument( '--loglevel', type=lambda x: getattr(logging, x), default=logging.WARNING, help='Set to DEBUG for verbose debugging output to stderr.') args = parser.parse_args() logging.basicConfig(level=args.loglevel) logging.getLogger("PIL.PngImagePlugin").setLevel(logging.WARNING) args.model = args.model.upper() try: qlr = BrotherQLRaster(args.model) except BrotherQLUnknownModel: sys.exit( "Unknown model. Use the command brother_ql_info list-models to show available models." ) try: label_type_specs[args.label_size] except ValueError: sys.exit( "Unknown label_size. Check available sizes with the command brother_ql_info list-label-sizes" ) qlr.exception_on_warning = True create_label(qlr, args.image, args.label_size, threshold=args.threshold, cut=args.cut, rotate=args.rotate) args.outfile.write(qlr.data)
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())
from brother_ql.conversion import convert from brother_ql.backends.helpers import send from brother_ql.raster import BrotherQLRaster # init config config = configparser.ConfigParser() config.read('/home/pi/stoneScanner/stone_scanner.ini') backend = config['printer']['backend'] # 'pyusb', 'linux_kernal', 'network' model = config['printer']['model'] # your printer model. printer = config['printer']['printer'] im = Image.open('/home/pi/stoneScanner/data/pic/stamp/stamp_result/stamp_0.png') qlr = BrotherQLRaster(model) qlr.exception_on_warning = True instructions = convert( qlr=qlr, images=[im], # Takes a list of file names or PIL objects. label=config['printer']['label'], dither=False, compress=False, red=bool(config['printer']['label']), # Only True if using Red/Black 62 mm label tape. dpi_600=False, lq=False, # True for low quality. no_cut=False ) printstate = send(instructions=instructions, printer_identifier=printer, backend_identifier=backend, blocking=True)
def main(): parser = argparse.ArgumentParser() parser.add_argument('image') parser.add_argument('outfile', nargs='?', type=argparse.FileType('wb'), default=stdout) parser.add_argument('--model', default='QL-500') parser.add_argument('--list-models', action='store_true', \ help='List available models and quit (the image argument is still required but ignored)') parser.add_argument('--threshold', type=int, default=170) parser.add_argument('--loglevel', type=lambda x: getattr(logging, x), default=logging.WARNING) args = parser.parse_args() logging.basicConfig(level=args.loglevel) args.model = args.model.upper() if args.list_models: print('Supported models:') print('\n'.join(models)) sys.exit(0) try: qlr = BrotherQLRaster(args.model) except BrotherQLUnknownModel: sys.exit("Unknown model. Use option --list-models to show available models.") qlr.exception_on_warning = True device_pixel_width = qlr.get_pixel_width() im = Image.open(args.image) hsize = int(im.size[1] / im.size[0] * device_pixel_width) im = im.resize((device_pixel_width, hsize), Image.ANTIALIAS) im = im.convert("L") arr = np.asarray(im, dtype=np.uint8) arr.flags.writeable = True white_idx = arr[:,:] < args.threshold black_idx = arr[:,:] >= args.threshold arr[white_idx] = 1 arr[black_idx] = 0 try: qlr.add_switch_mode() except BrotherQLUnsupportedCmd: pass qlr.add_invalidate() qlr.add_initialize() try: qlr.add_switch_mode() except BrotherQLUnsupportedCmd: pass qlr.add_status_information() qlr.mtype = 0x0A qlr.mwidth = 62 qlr.mlength = 0 qlr.add_media_and_quality(im.size[1]) try: qlr.add_autocut(True) qlr.add_cut_every(1) except BrotherQLUnsupportedCmd: pass try: qlr.dpi_600 = False qlr.cut_at_end = True qlr.add_expanded_mode() except BrotherQLUnsupportedCmd: pass qlr.add_margins() try: qlr.add_compression(True) except BrotherQLUnsupportedCmd: pass qlr.add_raster_data(arr) qlr.add_print() args.outfile.write(qlr.data)