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)
Beispiel #2
0
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
Beispiel #3
0
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
Beispiel #5
0
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)
Beispiel #6
0
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'))
Beispiel #7
0
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
Beispiel #8
0
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
Beispiel #9
0
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
Beispiel #10
0
    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
Beispiel #11
0
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)
Beispiel #12
0
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)
Beispiel #13
0
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')
Beispiel #14
0
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()
Beispiel #15
0
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)
Beispiel #16
0
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)
Beispiel #17
0
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 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)
Beispiel #19
0
def print_text(content=None):
    """
    More possible parameters:
    - alignment
    """

    return_dict = {'success': False}

    if content is None:
        return_dict['error'] = 'Please provide the text for the label'
        return return_dict

    threshold = 170
    fontsize = int(request.query.get('font_size', 100))
    width = 720
    margin = 0
    height = 100 + 2*margin

    try:
        font_family = request.query.get('font_family')
        font_style  = request.query.get('font_style')
        if font_family is None:
            font_family = DEFAULT_FONT['family']
            font_style =  DEFAULT_FONT['style']
        if font_style is None:
            font_style =  'Regular'
        font_path = FONTS[font_family][font_style]
    except KeyError:
        return_dict['error'] = "Couln't find the font & style"
        return return_dict

    im = Image.new('L', (width, height), 'white')
    draw = ImageDraw.Draw(im)
    im_font = ImageFont.truetype(font_path, fontsize)
    textsize = draw.textsize(content, font=im_font)
    vertical_offset = (height - textsize[1])//2
    horizontal_offset = max((width - textsize[0])//2, 0)
    if 'ttf' in font_path: vertical_offset -= 10
    offset = horizontal_offset, vertical_offset
    if DEBUG: print("Offset: {}".format(offset))
    draw.text(offset, content, (0), font=im_font)
    if DEBUG: im.save('sample-out.png')
    arr = np.asarray(im, dtype=np.uint8)
    arr.flags.writeable = True
    white_idx = arr[:,:] <  threshold
    black_idx = arr[:,:] >= threshold
    arr[white_idx] = 1
    arr[black_idx] = 0

    qlr = BrotherQLRaster(MODEL)
    qlr.add_switch_mode()
    qlr.add_invalidate()
    qlr.add_initialize()
    qlr.add_status_information()
    qlr.mtype = 0x0A
    qlr.mwidth = 62
    qlr.mlength = 0
    qlr.add_media_and_quality(im.size[1])
    qlr.add_autocut(True)
    qlr.add_cut_every(1)
    qlr.dpi_600 = False
    qlr.cut_at_end = True
    qlr.add_expanded_mode()
    qlr.add_margins()
    qlr.add_compression(True)
    qlr.add_raster_data(arr)
    qlr.add_print()

    if not DEBUG:
        try:
            be = BACKEND_CLASS(BACKEND_STRING_DESCR)
            be.write(qlr.data)
            be.dispose()
            del be
        except Exception as e:
            return_dict['message'] = str(e)
            logger.warning('Exception happened: %s', e)
            response.status = 500
            return return_dict

    return_dict['success'] = True
    if DEBUG: return_dict['data'] = str(qlr.data)
    return return_dict
Beispiel #20
0
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)
Beispiel #21
0
    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())
Beispiel #22
0
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
)