Using the Python win32 API wrapper, I want to select a specific printer, then use that printer to print a pdf file. I wrote this function:
import win32print
def send_to_printer(pdf_file_path, printer_name):
try:
# Get a handle to the printer
printer_handle = win32print.OpenPrinter(printer_name)
# Set up the document info as a sequence of three elements
doc_info = ("My Document", None, "RAW")
# Start the printing job
job_handle = win32print.StartDocPrinter(printer_handle, 1, doc_info)
# Open the PDF file
pdf_file = open(pdf_file_path, 'rb')
try:
# Read and print the content of the PDF file
data = pdf_file.read()
win32print.StartPagePrinter(printer_handle)
win32print.WritePrinter(printer_handle, data)
win32print.EndPagePrinter(printer_handle)
finally:
# Close the PDF file and end the printing job
pdf_file.close()
win32print.EndDocPrinter(printer_handle)
win32print.ClosePrinter(printer_handle)
print(f"Printing completed on {printer_name}")
except Exception as e:
print(f"Error printing the PDF: {e}")
and tested it like so:
printer = 'Zebra 450 ZPL'
pdf = 'myfile.pdf'
# This should print out a hard copy of my PDF
send_to_printer(printer, pdf)
When I try this, it seems like everything is working (on Windows 10). The PDF file is sent to the printer, and the printer processes the PDF (the file disappears in the printing pool), but nothing comes out of the actual printer. After that, my printer (Zebra 450 ZPL) is unable to print anything else unless I turn it off and on again.
What is wrong with the code, and how do I fix it?