Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
2.3 kB
1
Indexable
Never
import barcode
from barcode.writer import ImageWriter
from PIL import Image
import os
import platform
import subprocess

def get_printers():
    if platform.system() == 'Windows':
        cmd = "powershell \"Get-Printer | Select Name\""
        result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, shell=True)
        printer_lines = result.stdout.splitlines()
        printers = [line.strip() for line in printer_lines if line.strip()]
    else:
        result = subprocess.run(['lpstat', '-p', '-d'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
        printer_lines = result.stdout.splitlines()
        printers = [line.split(' ')[1] for line in printer_lines if line.startswith('printer')]

    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=ImageWriter(), add_checksum=False)
    output = barcode_image.save('temp_barcode')
    return output

def print_barcode(printer, barcode_image):
    temp_filename = barcode_image

    if platform.system() == 'Windows':
        os.system(f'print /D:"{printer}" {temp_filename}')
    else:
        os.system(f'lp -d {printer} -o media=Custom.1x2.125in -o fit-to-page {temp_filename}')

    os.remove(temp_filename)

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)
        print("Barcode printed successfully.")

        continue_printing = input("Do you want to print another barcode? (y/n): ")
        if continue_printing.lower() != 'y':
            break

if __name__ == "__main__":
    main()