今天使用python win32com调用金山wps报错,最后找到了解决办法

今天想学习一下怎样用python调用打印机打印文档,网上找了代码如下:
import win32print
import win32com.client
from PIL import Image, ImageWin
#import _imaging

def print_docfile(imagefilename): #打印doc文件
word = win32com.client.DispatchEx(‘kwps.Application’)
#调用word程序
word.Visible = 0
word.DisplayAlerts = 0
#不在前台显示文档及错误,在实际使用阶段可以全部关闭,提高运行速度,但是在调试时打开还是用处挺大的,可以对操作是否实现自己的需求进行直观的判断,比如说我们选中的内容是否已经高亮等等。
doc = word.Documents.Open(imagefilename)
doc.PrintOut()
doc.Close()
imagefilename = ‘d:/dayintupian.docx’
print_docfile(imagefilename)

因为我的机器上只有wps,运行后报错。如下:

*** Remote Interpreter Reinitialized ***
Traceback (most recent call last):
File “C:\Users\Administrator\AppData\Local\Programs\Python\Python37-32\lib\site-packages\win32com\client\dynamic.py”, line 89, in _GetGoodDispatch
IDispatch = pythoncom.connect(IDispatch)
pywintypes.com_error: (-2147221005, ‘无效的类字符串’, None, None)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File “C:\Users\Administrator\Desktop\printfile1.py”, line 16, in
print_docfile(imagefilename)
File “C:\Users\Administrator\Desktop\printfile1.py”, line 7, in print_docfile
word = win32com.client.Dispatch(“wps.Application”)
File “C:\Users\Administrator\AppData\Local\Programs\Python\Python37-32\lib\site-packages\win32com\client_init_.py”, line 95, in Dispatch
dispatch, userName = dynamic._GetGoodDispatchAndUserName(dispatch,userName,clsctx)
File “C:\Users\Administrator\AppData\Local\Programs\Python\Python37-32\lib\site-packages\win32com\client\dynamic.py”, line 114, in _GetGoodDispatchAndUserName
return (_GetGoodDispatch(IDispatch, clsctx), userName)
File “C:\Users\Administrator\AppData\Local\Programs\Python\Python37-32\lib\site-packages\win32com\client\dynamic.py”, line 91, in _GetGoodDispatch
IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx, pythoncom.IID_IDispatch)
pywintypes.com_error: (-2147221005, ‘无效的类字符串’, None, None)

查了资料将“word = win32com.client.Dispatch(‘wps.Application’)”,修改为“word = win32com.client.DispatchEx(‘wps.Application’)”,也不行。然后发现网上的文章说pythoncom接口和wps的版本有关,尝试着修改为“win32com.client.DispatchEx(‘kwps.Application’)”,结果报错信息发生了变化如下:
Traceback (most recent call last):
File “C:\Users\Administrator\Desktop\printfile1.py”, line 16, in
print_docfile(imagefilename)
File “C:\Users\Administrator\Desktop\printfile1.py”, line 12, in print_docfile
doc = word.Documents.Open(imagefilename)
File “”, line 8, in Open
pywintypes.com_error: (-2147352567, ‘发生意外。’, (0, ‘Kingsoft WPS’, ‘文档打开失败。’, ‘’, 3010, -786427), None)

个人感觉有戏,感觉接近成功了,继续在网上找资料,最后有大牛说是文件需要绝对路径,于是将文件路径修改为绝对路径**imagefilename = r’d:\dayin\tupian.docx’,**终于解决问题,可以正常打印。特此记录。

你可能感兴趣的:(python)