Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
2.4 kB
1
Indexable
Never
import treepoem
from io import BytesIO
import os
import platform
import subprocess

def get_printers():
    if platform.system() == 'Windows':
        cmd = "powershell \"Get-WmiObject -Query 'Select * From Win32_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):
    barcode_image = treepoem.generate_barcode(barcode_type='code128', data=product_code)
    output = BytesIO()
    barcode_image.save(output, format='PNG')
    return output.getvalue()

def print_barcode(printer, barcode_image):
    temp_filename = 'temp_barcode.png'

    with open(temp_filename, 'wb') as f:
        f.write(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()