Python Printing from python32

自闭症网瘾萝莉.ら 提交于 2019-12-08 04:05:42

问题


I can't get Python to print a word doc. What I am trying to do is to open the Word document, print it and close it. I can open Word and the Word document:

import win32com.client

msword = win32com.client.Dispatch("Word.Application") 
msword.Documents.Open("X:\Backoffice\Adam\checklist.docx")

msword.visible= True

I have tried next to print

msword.activedocument.printout("X:\Backoffice\Adam\checklist.docx")

I get the error of "print out not valid".

Could someone shed some light on this how I can print this file from Python. I think it might be as simple as changing the word "printout". Thanks, I'm new to Python.


回答1:


msword.ActiveDocument gives you the current active document. The PrintOut method prints that document: it doesn't take a document filename as a parameter.

From http://msdn.microsoft.com/en-us/library/aa220363(v=office.11).aspx:

expression.PrintOut(Background, Append, Range, OutputFileName, From, To, Item, 
  Copies, Pages, PageType, PrintToFile, Collate, FileName, ActivePrinterMacGX, 
  ManualDuplexPrint, PrintZoomColumn, PrintZoomRow, PrintZoomPaperWidth, 
  PrintZoomPaperHeight)

Specifically Word is trying to use your filename as a boolean Background which may be set True to print in the background.

Edit: Case matters and the error is a bit bizarre. msword.ActiveDocument.Printout() should print it. msword.ActiveDocument.printout() throws an error complaining that 'PrintOut' is not a property.

I think what happens internally is that Python tries to compensate when you don't match the case on properties but it doesn't get it quite right for methods. Or something like that anyway. ActiveDocument and activedocument are interchangeable but PrintOut and printout aren't.




回答2:


You probably have to escape the backslash character \ with \\:

msword.Documents.Open("X:\\Backoffice\\Adam\\checklist.docx")

EDIT: Explanation

The backslash is usually used to declare special characters. For example \n is the special character for a new-line. If you want a literal \ you have to escape it.



来源:https://stackoverflow.com/questions/7993387/python-printing-from-python32

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!