st-ten-1/src/components/brother_label_printer.py
2024-05-27 13:35:31 +02:00

64 lines
2.1 KiB
Python

import logging
import os
import platform
if platform.system().lower() == "windows":
import win32print
import win32ui
from PIL import Image, ImageDraw, ImageFont, ImageOps, ImageWin
import qrcode
from .component import Component
class BrotherLabelPrinter(Component):
def __int__(self):
self.log = logging.getLogger()
def print_label(self, barcode):
printer_name = win32print.GetDefaultPrinter()
file_name = "./tmp/tmp.png"
qr = qrcode.QRCode(
version=1,
error_correction=qrcode.constants.ERROR_CORRECT_L,
box_size=10,
border=4,
)
qr.add_data(barcode)
qr.make(fit=True)
try:
barcode_img = qr.make_image(fill_color="black", back_color="white")
barcode_img = barcode_img.resize((250, 250))
print_width = 720
print_height = 380
label_img = Image.new("RGB", (print_width, print_height), color=(255, 255, 255))
label_img.paste(barcode_img, box=(20, 20))
draw = ImageDraw.Draw(label_img)
font = ImageFont.truetype("config/label_templates/Fonts/FreeSansBold.ttf", 40)
font2 = ImageFont.truetype("config/label_templates/Fonts/FreeSansBold.ttf", 28)
draw.text((280, 50), "ST-TEN-10", (0, 0, 0), font=font)
draw.text((280, 150), barcode, (0, 0, 0), font=font2)
if not os.path.exists("./tmp/"):
os.makedirs("./tmp/")
label_img.save(file_name)
hdc = win32ui.CreateDC()
hdc.CreatePrinterDC(printer_name)
hdc.StartDoc(file_name)
hdc.StartPage()
dib = ImageWin.Dib(label_img.rotate(90, expand=True)) # Ruota di 270 gradi per stampare correttamente
dib.draw(hdc.GetHandleOutput(), (0, 0, print_height, print_width)) # Inverto larghezza e altezza
hdc.EndPage()
hdc.EndDoc()
return barcode
except Exception as e:
self.log.error("Errore durante la stampa dell'etichetta\n\nErrore:\n" + str(e))
return "ERRORE STAMPA"