mhammond / pywin32

Python for Windows (pywin32) Extensions
4.9k stars 783 forks source link

'win32ui' has no attribute 'CreatePrinterDC' #2293

Closed Ashish3080 closed 2 weeks ago

Ashish3080 commented 2 weeks ago

I am trying to print a pdf file to a specific printer using win32print. I am using this code: import win32print import win32ui import win32com.client import os

def print_pdf_to_printer(printer_name, pdf_path):

printer_handle = win32print.OpenPrinter(printer_name)

try:
    default_printer_info = win32print.GetPrinter(printer_handle, 2)
    printer_info = default_printer_info.copy()
    printer_info['pDevMode'].DriverData = b'RAW'
    pdf_file = open(pdf_path, 'rb')
    printer = win32ui.CreatePrinterDC(printer_name)
    printer.StartDoc(pdf_file_path)
    printer.StartPage()
    pdf_data = pdf_file.read()
    printer.Write(pdf_data)
    printer.EndPage()
    printer.EndDoc()

except Exception as e:
    print("Exception occurred: ",e)    

finally:

    win32print.ClosePrinter(printer_handle)
    pdf_file.close()

if name == "main":

# Replace 'Your Printer Name' with the actual name of the printer you want to use
selected_printer = 'Your Printer Name'

# Replace this with the path to your PDF file
pdf_file_path = "path/to/your/file.pdf"

if os.path.exists(pdf_file_path):
    print(f"Printing '{pdf_file_path}' to '{selected_printer}'...")
    print_pdf_to_printer(selected_printer, pdf_file_path)
    print("Printing complete.")
else:
    print(f"PDF file not found at '{pdf_file_path}'.")

I have not been able to get any further as I get this error "Exception occurred: module 'win32ui' has no attribute 'CreatePrinterDC'. and I have to select the default printer and using 'ctrl' + 'p' as hoteky to print the file. Please if anyone can anyone provide the solution to the issue or if can anyone tell how can i use python to print files on a specific printer without the need of downloading an .exe file.

mhammond commented 2 weeks ago

win32ui is not expected to have CreatePrinterDC. I don't know enough about printing to help, but the instructions you deleted re following the instructions at https://github.com/mhammond/pywin32#support would have found people who might.