def post_upload_mips_gate_record(): return_code = RETURN_CODE_FAILURE return_msg = RETURN_MSG_FAILURE response = {RETURN_CODE: return_code, RETURN_MSG: return_msg} try: filepath = '' req_info = decode_input(json.loads(request.data)) image_base64 = req_info['checkPic'] print(f'->> Got visitor photo ({image_base64[:10]})...') image_decoded = base64.b64decode(parse.unquote(image_base64)) # print('->> Creating badge...') badge_image = badge_factory.create_badge(req_info['name'], datetime.now().strftime('%m/%d/%Y'), image_decoded) print(f'->> Created badge with {len(badge_image)} bytes...') image_buffer = BytesIO(badge_image) with Image.open(image_buffer) as fil_image: filepath = IMG_FOLDER + req_info['name'] \ + datetime.now().strftime('_%Y%m%d_%H%M%S') \ + '.png' print(f'->> Saving badge image to {filepath}...') fil_image.save(filepath, 'PNG') with open(filepath, 'rb') as fp: print_data = brother_ql.brother_ql_create.convert(BrotherQLRaster('QL-800'), [fp], '62', dither=True) send(print_data, PRINTER_IDENTIFIER) print('->> Printed visitor badge...') response[RETURN_CODE] = RETURN_CODE_SUCCESS response[RETURN_MSG] = RETURN_MSG_SUCCESS return jsonify(response) except Exception as ex: print(ex) response[RETURN_MSG] = ex return jsonify(response), 400
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 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_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 printLabel(image): from brother_ql.raster import BrotherQLRaster from brother_ql.conversion import convert from brother_ql.backends.helpers import send send_to_printer = True if send_to_printer: backend = 'pyusb' model = 'QL-570' printer = 'usb://0x04f9:0x2028/C7Z863490' qlr = BrotherQLRaster(model) convert(qlr, image, '62') try: send(instructions=qlr.data, printer_identifier=printer, backend_identifier=backend, blocking=True) except: click.echo("Printer not connected") time.sleep(2) else: for i in image: i.show() pass
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 print_label(label): qlr = BrotherQLRaster(PRINTER_MODEL) qlr = convert(qlr, [label], LABEL_TYPE) return send(instructions=qlr, printer_identifier=PRINTER_URL, backend_identifier=PRINTER_BACKEND, blocking=True)
def __init__(self, obj_id: str, pose: Pose, collision_model: Optional[Models] = None) -> None: super(QL700, self).__init__(obj_id, pose, collision_model) self.qlr = BrotherQLRaster("QL-700") self.qlr.exception_on_warning = True
def send_to_printer(path): printer = BrotherQLRaster('QL-570') print_data = brother_ql.brother_ql_create.convert(printer, [path], '29x90', dither=True, rotate="auto", hq=False) send(print_data, PRINTER_IDENTIFIER)
def sendToPrinter(path): # Using USB connected printer PRINTER_IDENTIFIER = '/dev/usb/lp0' printer = BrotherQLRaster('QL-800') filename = path print_data = brother_ql.brother_ql_create.convert(printer, [filename], '62', dither=True,red=False) send(print_data, PRINTER_IDENTIFIER) #sendToPrinter('/home/pi/stoneScanner/data/pic/stamp/stamp_result/stamp_245.png')
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 main(): config_parser = ConfigParser() config_parser.read(CONFIG_FILE) config = config_parser['Main'] api = QcosApi(config['api_url']) ticket_width = int(config['ticket_width']) ticket_height = int(config['ticket_height']) while True: ticket = api.get_printable_ticket() if ticket is not None: print(ticket) ticket_info = api.get_ticket_info(ticket['ticket_info']) print(ticket_info) fee = api.get_fee(ticket_info['fee']) print(fee) camp = api.get_camp(fee['camp']) print(camp) registration = api.get_registration(ticket_info['registration']) print(registration) clan = api.get_clan(registration['clan']) print(clan) ticket_image = Image.new('RGB', (ticket_width, ticket_height), color=(255, 255, 255)) ticket_draw = ImageDraw.Draw(ticket_image) pos = draw_text(ticket_draw, camp['name'], (10, 0), ticket_width, ticket_height * 0.25) pos = draw_text(ticket_draw, clan['name'], (10, pos[1]), ticket_width, ticket_height * 0.1) pos = draw_text(ticket_draw, fee['name'], (10, pos[1]), ticket_width, ticket_height * 0.1) draw_text(ticket_draw, ticket['guid'], (10, pos[1]), ticket_width, ticket_height * 0.05) qr = QRCode(version=1, error_correction=ERROR_CORRECT_M, box_size=10, border=4) qr.add_data(ticket['guid']) qr_img = qr.make_image(fill_color="black", bakc_color="white") ticket_image.paste(qr_img, (10, int(ticket_height / 2))) ticket_image.save(config['temp_file']) qlr = BrotherQLRaster(config['model']) create_label(qlr, "test.png", '62') with open(config['printer_path'], 'wb') as file: file.write(qlr.data) api.mark_ticket_printed(ticket) sleep(2)
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 main(config, log): if config.g: config.identifiers = [ generate_id(config.prefix, k=config.size) for i in range(config.g) ] if not config.printer_pretend: if not config.printer_id: available_devices = brother_ql.backends.helpers.discover( backend_identifier=config.printer_backend) if not available_devices: sys.exit("No printers found") config.printer_id = available_devices[0]['identifier'] log.info('autoselected printer', printer=config.printer_id) ids_processed = [] for id in config.identifiers: if id == '-': for line in sys.stdin: line = line.strip() if len(line) == 0: continue ids_processed.append(line) else: ids_processed.append(id) labels = [generate_label(id) for id in ids_processed] if config.printer_pretend: for (i, image) in enumerate(labels): filename = f'labels_{i}.png' log.info('saving bitmap', file=filename) image.save(filename) else: qlr = BrotherQLRaster(config.printer_model) instructions = brother_ql.conversion.convert( qlr=qlr, images=labels, label=config.printer_label) brother_ql.backends.helpers.send( instructions=instructions, printer_identifier=config.printer_id, backend_identifier=config.printer_backend, blocking=True) print('\n'.join(ids_processed))
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)
from PIL import Image 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 )
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)