Clicking Windows Print Button to saving file

28 views Asked by At

Clicking Print Button to save a file

I want to create a python third party application which does the following. When I open a file(docx, pdf or csv) and opens the print dialog and click print. Upon clicking print, it should save the file in a local directory i.e. d:/prints . Note that in my application should be able to save the files even the printer or printers are offline. I have tried multiple things but i am not able to achieve my goal. Can you please help me. Thankyou

I came across this code given below and this is how it works: When i open a file and press ctrl+p, it creates an empty corrupt pdf in prints directory. Which is not the result i want, i want that on clicking a print button, it should save or copy the file in the directory.

import ctypes
import time
import os

save_directory = "D:/prints"


def is_ctrl_p_pressed():
    return (ctypes.windll.user32.GetKeyState(0x11) & 0x8000) != 0 and \
        (ctypes.windll.user32.GetKeyState(0x50) & 0x8000) != 0


try:
    while True:
        if is_ctrl_p_pressed():
            print("Ctrl+P was pressed. Detected print action.")

            # Check if the save directory exists, and create it if not
            if not os.path.exists(save_directory):
                os.makedirs(save_directory)

            # Generate a unique filename for the saved print document
            current_time = time.strftime("%Y%m%d-%H%M%S")
            save_filename = os.path.join(save_directory, f"print_{current_time}.pdf")

            # Replace the following line with your code to save the print job to the specified file
            # You might need to access the print spooler or printer driver to do this
            # For simplicity, we'll just create an empty file here.
            with open(save_filename, 'w') as f:
                pass

            print(f"Print document saved to: {save_filename}")
        time.sleep(0.1)  # Adjust the sleep duration as needed
except KeyboardInterrupt:
    pass
0

There are 0 answers