单击Windows打印按钮保存文件

Clicking Windows Print Button to saving file

提问人:Rehan Mahmood 提问时间:11/7/2023 更新时间:11/7/2023 访问量:19

问:

单击打印按钮保存文件

我想创建一个python第三方应用程序,它执行以下操作。 当我打开一个文件(docx、pdf 或 csv)并打开打印对话框并单击打印时。单击打印后,它应该将文件保存在本地目录中,即 d:/prints 。请注意,在我的应用程序中,即使打印机或打印机处于离线状态,也应该能够保存文件。我尝试了多种方法,但我无法实现我的目标。你能帮帮我吗?谢谢

我遇到了下面给出的这段代码,这就是它的工作原理: 当我打开一个文件并按ctrl + p时,它会在prints目录中创建一个空的损坏的pdf。这不是我想要的结果,我希望在单击打印按钮时,它应该在目录中保存或复制文件。

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
Python 打印 端口 后台处理程序

评论


答: 暂无答案