I have a problem with getting a hardcopy working. The printer has been checked and used in different apps but this code will NOT get the printer to respond. It shows no errors but just sits doing nothing! Code follows:-
import win32print
import win32ui
def print_file(file_path):
printer_name = win32print.GetDefaultPrinter()
hprinter = win32print.OpenPrinter(printer_name)
printer_dc = win32ui.CreateDC()
printer_dc.CreatePrinterDC(printer_name)
printer_dc.StartDoc('Print Document')
printer_dc.StartPage()
try:
with open(file_path, 'r') as file:
lines = file.readlines()
for line in lines:
# Split the line into fields (assuming fields are separated by commas)
fields = line.strip().split(',')
# Format the fields for printing (customize this formatting as needed)
formatted_line = f"First Name: {fields[0]}, " \
f"Middle Name: {fields[1]}, " \
f"Surname: {fields[2]}, " \
f"Birthdate: {fields[3]}, " \
f"Age: {fields[4]}\n"
printer_dc.TextOut(100, 100, formatted_line)
except Exception as e:
print(f"Error printing file: {str(e)}")
printer_dc.EndPage()
printer_dc.EndDoc()
printer_dc.DeleteDC()
win32print.ClosePrinter(hprinter)
if name == ‘__main’:
file_to_print = r’C:\users\pc\documents\user_info.txt’
print_file(file_to_print)