Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
2.7 kB
2
Indexable
Never
import io
import code128
from PIL import Image, ImageDraw, ImageFont, ImageWin
import os
import win32print
import win32ui

def get_printers():
    printers = [printer[2] for printer in win32print.EnumPrinters(win32print.PRINTER_ENUM_LOCAL)]
    return printers

def user_select_printer(printers):
    if not printers:
        print("No printers found.")
        return None

    print("List of printers:")
    for i, printer in enumerate(printers, start=1):
        print(f"{i}. {printer}")

    selected_index = int(input("Enter the number of the printer you'd like to use: "))
    return printers[selected_index - 1]

def get_product_code():
    product_code = input("Enter the product code: ")
    return product_code.upper()

def generate_custom_code128(product_code, dpi=300, paper_size=(1, 2.125)):
    barcode = code128.image(product_code, thickness=4, height=int(1.5 * dpi))
    paper_width = int(paper_size[0] * dpi)
    paper_height = int(paper_size[1] * dpi)
    image = Image.new('1', (paper_width, paper_height), 1)
    barcode = barcode.rotate(90, expand=True)
    barcode_width, barcode_height = barcode.size
    x_pos = int((paper_width - barcode_width) / 2)
    y_pos = int((paper_height - barcode_height) / 2)
    image.paste(barcode, (x_pos, y_pos))
    draw = ImageDraw.Draw(image)
    font = ImageFont.truetype("arial.ttf", 10)
    text_width, text_height = draw.textsize(product_code, font=font)
    text_x = x_pos + barcode_width + 2
    text_y = int((paper_height - text_height) / 2)
    draw.text((text_x, text_y), product_code, font=font, fill=0)
    output = io.BytesIO()
    image.save(output, format="PNG")
    output.seek(0)
    return output

def generate_barcode(product_code):
    output_filename = 'temp_barcode'
    barcode_image = generate_custom_code128(product_code)
    with open(output_filename + '.png', 'wb') as f:
        f.write(barcode_image.getvalue())
    return output_filename

def print_barcode(printer, barcode_image):
    printer_dc = win32ui.CreateDC()
    printer_dc.CreatePrinterDC(printer)
    page_size_mm = (25.4, 54)
    dpi = 300
    page_size_pixels = tuple(int(dpi * page_size_mm[i] / 25.4) for i in (0, 1))
    image = Image.open(barcode_image+".png")
    image_width, image_height = image.size
    x_pos = int((page_size_pixels[0] - image_width) / 2)
    y_pos = int((page_size_pixels[1] - image_height) / 2)
    printer_dc.StartDoc(barcode_image+".png")
    printer_dc.StartPage()
    dib = ImageWin.Dib(image)
    dib.draw(printer_dc.GetSafeHdc(), (x_pos, y_pos, image_width, image_height))
    printer_dc.EndPage()
    printer_dc.EndDoc()
    printer_dc.DeleteDC()

def main():
    product_code = get_product_code()
    barcode_image = generate_barcode(product_code