Python 选择特定打印机打印pdf文件

问题描述 投票:0回答:1

使用Python win32 API包装器,我想选择一个特定的打印机,然后使用该打印机打印pdf文件。我写了这个函数:

import win32print

def send_to_printer(pdf_file_path, printer_name):
    try:
        # Get a handle to the printer
        printer_handle = win32print.OpenPrinter(printer_name)

        # Set up the document info as a sequence of three elements
        doc_info = ("My Document", None, "RAW")

        # Start the printing job
        job_handle = win32print.StartDocPrinter(printer_handle, 1, doc_info)

        # Open the PDF file
        pdf_file = open(pdf_file_path, 'rb')

        try:
            # Read and print the content of the PDF file
            data = pdf_file.read()
            win32print.StartPagePrinter(printer_handle)
            win32print.WritePrinter(printer_handle, data)
            win32print.EndPagePrinter(printer_handle)

        finally:
            # Close the PDF file and end the printing job
            pdf_file.close()
            win32print.EndDocPrinter(printer_handle)
            win32print.ClosePrinter(printer_handle)

        print(f"Printing completed on {printer_name}")
    except Exception as e:
        print(f"Error printing the PDF: {e}")

并像这样测试它:

printer = 'Zebra 450 ZPL'
pdf = 'myfile.pdf'

# This should print out a hard copy of my PDF
send_to_printer(printer, pdf)

当我尝试此操作时,似乎一切正常(在 Windows 10 上)。 PDF 文件被发送到打印机,打印机处理 PDF(文件在打印池中消失),但实际打印机没有输出任何内容。之后,我的打印机(Zebra 450 ZPL)无法打印任何其他内容,除非我将其关闭然后再次打开。

代码有什么问题,如何修复?

python printing pywin32
1个回答
0
投票

我一直在使用此脚本通过我的脚本从打印机打印 QRCodes。看看是否有帮助:

安装
pywin32
pip install pywin32
查看可用打印机的名称
import win32print

def get_available_printer_names():
    printer_names = []
    flags = win32print.PRINTER_ENUM_LOCAL | win32print.PRINTER_ENUM_CONNECTIONS
    
    printers = win32print.EnumPrinters(flags)
    for printer in printers:
        printer_name = printer['pPrinterName']
        printer_names.append(printer_name)
    
    return printer_names

if __name__ == "__main__":
    available_printers = get_available_printer_names()
    if available_printers:
        print("Available printers:")
        for printer_name in available_printers:
            print(printer_name)
    else:
        print("No printers found.")
输入您的打印机名称和
.pdf
路径
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}'.")

© www.soinside.com 2019 - 2024. All rights reserved.