Beispiel #1
0
    def __init__(self, picname: str,
                 config: tp.Dict[str, tp.Dict[str, tp.Any]]) -> None:
        """
        :param picname: path to a picture to be printed
        :type picname: str

        When creating an instance of the class, it creates a task for a brother QL-800 printer to print a label with a
        qr-code passed as an argument. picname != qrpic, it contains side fields and logos (optionally)
        """

        logging.info("Initializing printer")

        qr = Image.open(picname)
        printer_config: tp.Dict[str, tp.Any] = config["printer"]
        printer: str = printer_config["address"]  # link to device
        label_name = str(printer_config["paper_width"]
                         )  # that depends on paper used for printing

        logging.info("Printing...")
        qlr = BrotherQLRaster(printer_config["printer_model"])
        red: bool = (label_name == "62")
        conversion.convert(qlr, [qr], label_name, red=red)
        send(
            qlr.data, printer
        )  # this is some standard code for printing with brother label printer with python,
        # red = True means that black and red printing will be done. Only for 62 label paper
        logging.info("Printed!")
Beispiel #2
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
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 #4
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 #5
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
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 #7
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 #8
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 #9
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 #10
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 #11
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'])
Beispiel #12
0
def printLabel(name):
    width = 500
    height = 100

    d = Drawing(width, height)
    d.add(String(5, 5, name, fontSize=40, fontName='Helvetica'))
    #d.add(String(5, 5, name, fontSize=60, fontName='Helvetica'))

    qlr = BrotherQLRaster('QL-1050')
    #qlr = BrotherQLRaster('QL-800')
    create_label(qlr,
                 renderPM.drawToPIL(d),
                 LABEL_NAME,
                 rotate=0,
                 cut=True,
                 dpi_600=DPI_600)
    send(qlr.data, PRINTER)
Beispiel #13
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 #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 cut(self) -> None:

        # kind of hack (it is so far not possible to only perform cut)
        img = Image.new('RGB', (PX_WIDTH, 1), (255, 255, 255))
        status = send(instructions=convert(self.qlr, [img], "62"),
                      printer_identifier="usb://0x04f9:0x2042",
                      backend_identifier="pyusb",
                      blocking=True)

        if False in (status["did_print"], status["ready_for_next_job"]):
            raise QL700Exception()
Beispiel #16
0
    def __init__(self, picname: str) -> None:
        """
        :param picname: path to a picture to be printed
        :type picname: str

        When creating an instance of the class, it creates a task for a brother QL-800 printer to print a label with a
        qr-code passed as an argument. picname != qrpic, it contains side fields and logos (optionally)
        """
        logging.warning("Initializing printer")

        qr = Image.open(picname)

        printer = "usb://0x04f9:0x209b"  # link to device on RPI
        label_name = "62"  # that depends on paper used for printing

        logging.warning("Printing...")
        qlr = BrotherQLRaster("QL-800")
        conversion.convert(qlr, [qr], label_name, red=True)
        send(
            qlr.data, printer
        )  # this is some standard code for printing with brother label printer with python,
        # red = True means that black and red printing will be done. Only for 62 label paper
        logging.warning("Printed!")
Beispiel #17
0
    def print(self, qr_text: str) -> None:

        qr = qrcode.make(qr_text)

        img = qr.get_image()
        img = img.resize((PX_WIDTH, PX_WIDTH))

        status = send(instructions=convert(self.qlr, [img], "62", cut=False),
                      printer_identifier="usb://0x04f9:0x2042",
                      backend_identifier="pyusb",
                      blocking=True)

        if False in (status["did_print"], status["ready_for_next_job"]):
            raise QL700Exception()
Beispiel #18
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 #19
0
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)
print(printstate['did_print'],printstate['ready_for_next_job'])
Beispiel #20
0
def send_cmd(ctx, *args, **kwargs):
    from brother_ql.backends.helpers import send
    send(instructions=kwargs['instructions'].read(),
         printer_identifier=ctx.meta.get('PRINTER'),
         backend_identifier=ctx.meta.get('BACKEND'),
         blocking=True)
Beispiel #21
0
def printLabel(user, eventName):
    FONT_NAME = "/usr/share/fonts/truetype/DejaVuSans.ttf"
    f17 = ImageFont.truetype(FONT_NAME, 17)
    f18 = ImageFont.truetype(FONT_NAME, 18)
    f25 = ImageFont.truetype(FONT_NAME, 25)
    f40 = ImageFont.truetype(FONT_NAME, 40)
    f80 = ImageFont.truetype(FONT_NAME, 80)
    f100 = ImageFont.truetype(FONT_NAME, 100)

    name = HumanName(user['Name'])

    ticket = user['Tickets'].split()
    if 'Abend' in user['Tickets']:
        ticket[0] += ' ' + ticket[1]

    mitarbeiter = False
    if 'Mitarbeiter' in user['Tickets']:
        mitarbeiter = True
    if 'Free' in user['Tickets']:
        mitarbeiter = True

    for i in range(2):
        img = Image.new("RGB", imgSize, fillWhite)
        draw = ImageDraw.Draw(img)

        printCenter(draw, 50, (name.first.capitalize() + ' ' + name.middle.capitalize()).strip(), f100)
        printCenter(draw, 170, name.last.capitalize(), f40)

        if i == 0:
            if mitarbeiter:
                printCenter(draw, 240, "Mitarbeiter", f80)

            printCenter(draw, 350, ticket[0] + ' (' + user['order'] + ')', f40)
            printCenter(draw, 400, eventName, f40)

            if 'Alter' in user:
                printCenter(draw, 450, "Alter: " + str(user['Alter']), f25)

            if 'Seminare und Workshops' in user:
                seminar = user['Seminare und Workshops'].split('(')
                printCenter(draw, 485, seminar[0], f25)
        else:
            text = """
Samstag
11.30 Uhr - “Zwischen Heimweh und Fernsucht”
13.00 Uhr - Mittagessen
14.30 Uhr - Seminare & Workshops
16.30 Uhr - “We will block you”
18.00 Uhr - Abendessen
20.00 Uhr - “Comming Home”
22.00 Uhr - Latenightangebote & Konzerte"""
            printLeft(draw, 0, 240, text, f17)

            text = """
Sonntag
08.00 Uhr - Frühstück
09.30 Uhr - “Dieser Weg wird kein Leichter sein”
12.00 Uhr - Mittagessen
13.30 Uhr - “Ist herzlich Willkommen übertrieben?”
14.30 Uhr - Abreise

Einlass jeweils 15 Minuten vor Veranstaltungsbeginn"""
            printLeft(draw, 450, 240, text, f17)

            text = """
Solltest du Erste Hilfe benötigen, erreichst du das Connect-Notfall-Team unter 
der Telefonnummer 0170 - 27 65 185 oder du meldest dich am Infopoint."""

            printLeft(draw, 0, 450, text, f18)

        img.save('tmp.png')

        qlr = BrotherQLRaster(CONFIG['printer'])
        qlr.exception_on_warning = True
        convert(qlr, ['tmp.png'], '54', cut=True, dither=False, compress=True, red=False, dpi_600=False, hq=True, rotate=90)
        send(instructions=qlr.data, printer_identifier=CONFIG['identifier'], backend_identifier=CONFIG['backend'], blocking=True)
def main():

    # Command line parsing...
    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(
        'printer',
        metavar='PRINTER_IDENTIFIER',
        nargs='?',
        help=
        'Identifier string specifying the printer. If not specified, selects the 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")

    # Reading the instruction input file into content variable
    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()

    # Setting up the requested level of logging.
    level = logging.DEBUG if args.debug else logging.INFO
    logging.basicConfig(level=level)

    # State any shortcomings of this software early on.
    if args.backend == 'network':
        logger.warning(
            "The network backend doesn't supply any 'readback' functionality. No status reports will be received."
        )

    # Select the backend based: Either explicitly stated or derived from identifier. Otherwise: Default.
    selected_backend = None
    if args.backend:
        selected_backend = args.backend
    else:
        try:
            selected_backend = guess_backend(args.printer)
        except:
            logger.info(
                "No backend stated. Selecting the default linux_kernel backend."
            )
            selected_backend = 'linux_kernel'

    # List any printers found, if explicitly asked to do so or if no identifier has been provided.
    if args.list_printers or not args.printer:
        available_devices = discover(backend_identifier=selected_backend)
        log_discovered_devices(available_devices)

    if args.list_printers:
        print(textual_description_discovered_devices(available_devices))
        sys.exit(0)

    # Determine the identifier. Either selecting the explicitly stated one or using the first found device.
    identifier = None
    if not args.printer:
        "We need to search for available devices and select the first."
        if not available_devices:
            sys.exit("No printer found")
        identifier = available_devices[0]['identifier']
        print("Selecting first device %s" % identifier)
    else:
        "A string identifier for the device was given, let's use it."
        identifier = args.printer

    # Finally, do the actual printing.
    send(instructions=content,
         printer_identifier=identifier,
         backend_identifier=selected_backend,
         blocking=True)