Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
2.1 kB
3
Indexable
Never
import barcode
from barcode.writer import SVGWriter
import os
import platform
import subprocess
import win32print
import tempfile
import img2pdf

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_barcode(product_code):
    Code128 = barcode.get_barcode_class('code128')
    barcode_image = Code128(product_code, writer=SVGWriter())
    output_filename = 'temp_barcode.svg'
    barcode_image.save(output_filename)
    return output_filename

def print_barcode(printer, barcode_image):
    # Convert the SVG image to PDF
    with open(barcode_image, 'rb') as f:
        svg_data = f.read()
    with tempfile.NamedTemporaryFile(suffix='.pdf', delete=False) as tf:
        tf.write(img2pdf.convert(svg_data))

    # Print the PDF file
    printer_name = win32print.GetDefaultPrinter()
    if printer_name != printer:
        win32print.SetDefaultPrinter(printer)
    win32api.ShellExecute(0, "print", tf.name, None, ".", 0)

    # Restore the default printer
    if printer_name != printer:
        win32print.SetDefaultPrinter(printer_name)

    # Delete the temporary PDF file
    os.remove(tf.name)

def main():
    printers = get_printers()
    selected_printer = user_select_printer(printers)

    if selected_printer is None:
        return

    while True:
        product_code = get_product_code()
        barcode_image = generate_barcode(product_code)
        print_barcode(selected_printer, barcode_image)
        os.remove(barcode_image)  # Delete the barcode image after printing


if __name__ == "__main__":
    main()