基于win32print进行相关操作,废话不多说直接上代码
选择打印机
printers = win32print.EnumPrinters(win32print.PRINTER_ENUM_LOCAL) # 获取本地打印机数据列表
for i, item in enumerate(printers):
printerName = item[2]) # 拿到打印机名称
打印文件
import win32print
import win32api
class Print:
@staticmethod
def print_file(filename, printer_name=None):
# 打开文件
file = open(filename, "rb")
data = file.read()
file.close()
# 获取默认打印机
if not printer_name or len(printer_name)==0: # 未选择打印机时使用默认打印机
printer_name = win32print.GetDefaultPrinter()
# 打印文件
hPrinter = win32print.OpenPrinter(printer_name) # 拿到具体的打印机
try:
hJob = win32print.StartDocPrinter(hPrinter, 1, ("测试报告", None, "RAW"))
try:
win32api.ShellExecute(0, "print", filename, None, ".", 0)
win32print.StartPagePrinter(hPrinter)
win32print.WritePrinter(hPrinter, data)
win32print.EndPagePrinter(hPrinter)
finally:
win32print.EndDocPrinter(hPrinter)
finally:
win32print.ClosePrinter(hPrinter)