Beispiel #1
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
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)