示例#1
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
示例#3
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!")
示例#4
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
示例#5
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_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)
示例#7
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)
示例#8
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()
示例#9
0
def create_label(qlr,
                 image,
                 label_size,
                 threshold=70,
                 cut=True,
                 dither=False,
                 compress=False,
                 red=False,
                 **kwargs):
    if not isinstance(image, list):
        image = [image]
    convert(qlr,
            image,
            label_size,
            threshold=threshold,
            cut=cut,
            dither=dither,
            compress=compress,
            red=red,
            **kwargs)
示例#10
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)
示例#11
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!")
示例#12
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'))
示例#13
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()
示例#14
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
示例#15
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()
def create_label(qlr, image, label_size, threshold=70, cut=True, dither=False, compress=False, red=False, **kwargs):
    convert(qlr, [image], label_size, threshold=threshold, cut=cut, dither=dither, compress=compress, red=red, **kwargs)
示例#17
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'])
示例#18
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)