在Python中,你可以使用第三方庫win32print
來調用打印機打印文檔。以下是一個簡單的示例代碼:
import win32print
import win32api
# 獲取默認打印機
printer_name = win32print.GetDefaultPrinter()
# 打開打印機
printer = win32print.OpenPrinter(printer_name)
# 打印文件
file_path = "path/to/your/document.txt"
with open(file_path, "rb") as file:
data = file.read()
job = win32print.StartDocPrinter(printer, 1, ("Document", None, "RAW"))
win32print.StartPagePrinter(printer)
win32print.WritePrinter(printer, data)
win32print.EndPagePrinter(printer)
win32print.EndDocPrinter(printer)
# 關閉打印機
win32print.ClosePrinter(printer)
這段代碼會將指定的文檔打印到默認打印機中。請確保你已經安裝了pywin32
庫,可以通過pip install pywin32
來安裝。同時,請將file_path
替換為你要打印的文檔路徑。