st-ten-1/src/components/brother_label_printer.py

64 lines
2.1 KiB
Python
Raw Normal View History

2024-03-12 12:48:00 +00:00
import logging
import os
2024-05-27 11:35:31 +00:00
import platform
if platform.system().lower() == "windows":
import win32print
import win32ui
2024-03-18 10:02:01 +00:00
from PIL import Image, ImageDraw, ImageFont, ImageOps, ImageWin
2024-03-14 12:15:08 +00:00
import qrcode
2024-03-12 12:48:00 +00:00
2024-03-21 13:30:03 +00:00
from .component import Component
2024-03-12 12:48:00 +00:00
class BrotherLabelPrinter(Component):
def __int__(self):
self.log = logging.getLogger()
2024-03-14 12:15:08 +00:00
def print_label(self, barcode):
2024-03-18 10:02:01 +00:00
printer_name = win32print.GetDefaultPrinter()
file_name = "./tmp/tmp.png"
2024-03-14 12:15:08 +00:00
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)
2024-03-12 12:48:00 +00:00
try:
2024-03-18 10:02:01 +00:00
barcode_img = qr.make_image(fill_color="black", back_color="white")
barcode_img = barcode_img.resize((250, 250))
2024-03-18 10:02:01 +00:00
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))
2024-03-12 12:48:00 +00:00
draw = ImageDraw.Draw(label_img)
2024-03-14 12:15:08 +00:00
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)
2024-03-14 12:15:08 +00:00
draw.text((280, 150), barcode, (0, 0, 0), font=font2)
2024-03-18 10:02:01 +00:00
if not os.path.exists("./tmp/"):
os.makedirs("./tmp/")
label_img.save(file_name)
2024-03-18 10:02:01 +00:00
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
2024-03-18 10:02:01 +00:00
dib.draw(hdc.GetHandleOutput(), (0, 0, print_height, print_width)) # Inverto larghezza e altezza
hdc.EndPage()
hdc.EndDoc()
2024-03-12 12:48:00 +00:00
return barcode
except Exception as e:
2024-03-18 10:02:01 +00:00
self.log.error("Errore durante la stampa dell'etichetta\n\nErrore:\n" + str(e))
return "ERRORE STAMPA"