Reputation: 1
I'm using the win32print API to send a document to a printer. Here is the code:
import win32print
import win32api
import os
import time
def list_printers():
printers = win32print.EnumPrinters(win32print.PRINTER_ENUM_LOCAL |win32print.PRINTER_ENUM_CONNECTIONS)
printer_list=[printer[2] for printer in printers]
return printer_list
def choose_printer(printers):
print("Available Printers:")
for i, printer in enumerate(printers):
print(f"{i + 1}. {printer}")
while True:
try:
choice = int(input("Select a printer by number: "))
if 1 <= choice <= len(printers):
return printers[choice - 1]
else:
print("Invalid choice. Please select a valid printer number.")
except ValueError:
print("Invalid input. Please enter a number.")
def print_pdf(pdf_path, printer_name):
if not os.path.exists(pdf_path):
raise FileNotFoundError(f"No such file: '{pdf_path}'")
print(f"Printing '{pdf_path}' to '{printer_name}'")
printer_handle = win32print.Ope
nPrinter(printer_name)
job_id = win32print.StartDocPrinter(printer_handle, 1, ("PDF Document",None,"RAW"))
try:
win32print.StartPagePrinter(printer_handle)
with open(pdf_path, 'rb') as pdf_file:
pdf_content = pdf_file.read()
# print(pdf_content)
# Write the PDF content to the printer
# time.sleep(4)
bytesPrinted=win32print.WritePrinter(printer_handle, pdf_content)
print(bytesPrinted)
win32print.EndPagePrinter(printer_handle)
finally:
win32print.EndDocPrinter(printer_handle)
win32print.ClosePrinter(printer_handle)
if __name__ == "__main__":
pdf_file_path = "C:/Users/DELL/Downloads/test.pdf"
printers = list_printers()
if not printers:
print("No printers found.")
else:
selected_printer=choose_printer(printers)
print_pdf(pdf_file_path,selected_printer)
I also tried using this method
win32api.ShellExecute(0, "printto",pdf_file_path,f'"{printername}"', ".", 0)
It gives the error: device attached to the system is not functioning. The first runs without any error but printer does not print out any page it just makes sound. Can you suggest what I'm doing wrong and if there is any alternative method which i can use.
Upvotes: 0
Views: 58