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())
output_filename = 'temp_barcode.png'
barcode_image.save(output_filename)
return output_filename
def print_barcode(printer, barcode_image):
if platform.system() == 'Windows':
os.system(f'print /D:"{printer}" {barcode_image}')
else:
os.system(f'lp -d {printer} -o media=Custom.1x2.125in -o fit-to-page {barcode_image}')
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()