def publisher(pubfile, psfile, printer): pythoncom.CoInitializeEx(pythoncom.COINIT_APARTMENTTHREADED) myPulisher = win32com.client.DispatchEx('Publisher.Application') myDoc = myPublisher.Open(pubfile,True,False,3); myDoc.ActivePrinter = printer myDoc.PrintOut(1,myDoc.Pages.Count,psfile,1,False) myDoc.Close() myPublisher.Quit() del myDoc del myPublisher pythoncom.CoUninitialize()
Create and write Text to a Word Document
import win32com.client wordapp = win32com.client.Dispatch("Word.Application") # Create new Word Object wordapp.Visible = 0 # Word Application should`t be visible worddoc = wordapp.Documents.Add() # Create new Document Object worddoc.PageSetup.Orientation = 1 # Make some Setup to the Document: worddoc.PageSetup.LeftMargin = 20 worddoc.PageSetup.TopMargin = 20 worddoc.PageSetup.BottomMargin = 20 worddoc.PageSetup.RightMargin = 20 worddoc.Content.Font.Size = 11 worddoc.Content.Paragraphs.TabStops.Add (100) worddoc.Content.Text = "Hello, I am a text!" worddoc.Content.MoveEnd worddoc.Close() # Close the Word Document (a save-Dialog pops up) wordapp.Quit() # Close the Word Application
Excel to PDF Converter as a Windows NT/2000 Service
This script is designed as a Windows 2000/NT Service and converts incoming Excel Workbooks in a directory to PDF. After installing this script with python scriptname.py install you will find a Service called “Excel2PDF” in the Service Control Manager (Services). To remove the Service do a python scriptname.py remove.
One Problem exists: The Service runs only when a user is logged in. If someone knows the problem please mail it via the contact webform.
To get the usage information start this script with the python interpreter as usually.
import win32serviceutil import win32service import win32event import win32gui import time import win32com.client import pythoncom import os class XLS2PDFService(win32serviceutil.ServiceFramework): _svc_name_ = "xls2pdf Service" _svc_display_name_ = "Excel2PDF" def __init__(self, args): win32serviceutil.ServiceFramework.__init__(self, args) self.hWaitStop = win32event.CreateEvent(None, 0, 0, None) def SvcStop(self): self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) win32event.SetEvent(self.hWaitStop) win32gui.MessageBox(0, "XLS2PDF Service has been stopped" , "XLS2PDF Status" , 0 ) def SvcDoRun(self): gscommand = 'c:\\gs\\gs8.15\\bin\\gswin32c.exe -sDEVICE=pdfwrite -r300 \ -dNOPAUSE -dBATCH -dSAFER -sPAPERSIZE=a4 \ -sOutputFile="'+path_to_watch+filename+'.pdf" "'+tmpfile+'"' path_to_watch = 'd:\\share\\' tmpdir = tempfile.mkdtemp() before = dict ([(f, None) for f in os.listdir (path_to_watch)]) win32gui.MessageBox(0, "XLS2PDF has been started" , "XLS2PDF Status" , 0 ) while 1 : time.sleep (0.1) after = dict ([(f, None) for f in os.listdir (path_to_watch)]) added = [f for f in after if not f in before] if added and added[0][-3:]=='xls': print os.tmpfile() filename = added[0] tmpfile = tmpdir + '\\'+filename+'.ps' if filename[-3:]=='xls': pythoncom.CoInitializeEx(pythoncom.COINIT_APARTMENTTHREADED) myExcel = win32com.client.DispatchEx('Excel.Application') Excel = myExcel.Workbooks.Open(path_to_watch + filename, 0, False, 2) Excel.PrintOut(1, 5000, 1, False, 'ServPDF', True, False, tmpfile) Excel.Saved = 1 Excel.Close() myExcel.Quit() del Excel del myExcel os.popen(gscommand) #os.remove(path_to_watch+filename) os.remove(tmpfile) pythoncom.CoUninitialize() before = after if __name__=='__main__': win32serviceutil.HandleCommandLine(XLS2PDFService)
A MS Office to Postscript Converter
This Python module can be used to convert files from Microsoft
Office to Postscript. Remember: To print out Postscript files from Microsoft Office you need a virtual Postscript printer.
Alternatively you can download this tool from here too.
import win32com.client, time, pythoncom """ MSOffice2PS - Microsoft Office to Postscript Converter 1.1 Makes a Postscript file from Word-, Excel- or Powerpoint. Now with mutex support for Powerpoint. Because Powerpoint can only run as a single instance. Line 57 must have a unique GUID. You can create a new GUID via: i mport pythoncom print pythoncom.CreateGuid() usage: first: import msoffice2ps in the script, where it should be used then call the convert-function. import msoffice2ps msoffice2ps.word('wordfilename', 'psfilename', 'ps_printername') msoffice2ps.excel('excelfilename', 'psfilename', 'ps_printername') msoffice2ps.powerpoint('powerpointfilename', 'psfilename', 'ps_printername') Dipl.-Ing. Mustafa Goermezer -> http://www.goermezer.de """ def word(wordfile, psfile, printer): pythoncom.CoInitializeEx(pythoncom.COINIT_APARTMENTTHREADED) myWord = win32com.client.DispatchEx('Word.Application') myWord.Application.ActivePrinter = printer myDoc = myWord.Documents.Open(wordfile, False, False, False) myDoc.Saved=1 myWord.Application.NormalTemplate.Saved = 1 myWord.PrintOut(True, False, 0, psfile) while myWord.BackgroundPrintingStatus > 0: time.sleep(0.1) myDoc.Close() myWord.Quit() del myDoc del myWord pythoncom.CoUninitialize() def excel(excelfile, psfile, printer): pythoncom.CoInitializeEx(pythoncom.COINIT_APARTMENTTHREADED) myExcel = win32com.client.DispatchEx('Excel.Application') myExcel.Application.AskToUpdateLinks = 0 Excel = myExcel.Workbooks.Open(excelfile, 0, False, 2) Excel.Saved = 1 Excel.PrintOut(1, 5000, 1, False, printer, True, False, psfile) Excel.Close() myExcel.Quit() del myExcel del Excel pythoncom.CoUninitialize() def powerpoint(powerpointfile, psfile, printer): from win32event import CreateMutex from win32api import GetLastError from winerror import ERROR_ALREADY_EXISTS from sys import exit #the guid in the next line must be unique !!! handle = CreateMutex ( None, 1, '{8620EF5C-7ED7-4A46-834B-3C9220566F69}' ) if GetLastError ( ) == ERROR_ALREADY_EXISTS: print 'Powerpoint conversion already working' exit ( 1 ) pythoncom.CoInitializeEx(pythoncom.COINIT_APARTMENTTHREADED) myPowerpoint = win32com.client.DispatchEx('Powerpoint.Application') myPpt = myPowerpoint.Presentations.Open(powerpointfile, False, False, False) myPpt.PrintOptions.PrintInBackground = 0 myPpt.PrintOptions.ActivePrinter = printer myPpt.Saved = 1 myPpt.PrintOut(1, 5000, psfile, 0, False) myPpt.Close() #myPowerpoint.Quit() del myPpt #del myPowerpoint pythoncom.CoUninitialize()
A simple Excel to PDF Converter
This is a simple PDF Converter which watches in a directory for
incoming Excel documents and converts them to PDF. Ghostscript and a
Postscript printer has to be installed.
path_to_watch = "D:\\share\\"
before = dict ([(f, None) for f in os.listdir (path_to_watch)]) def convert(filename): tmpfile = path_to_watch + 'tmp\\'+filename+'.ps' if filename[-3:]=='xls': pythoncom.CoInitializeEx(pythoncom.COINIT_APARTMENTTHREADED) myExcel = win32com.client.DispatchEx('Excel.Application') Excel = myExcel.Workbooks.Open(path_to_watch+filename, 0, False, 2) Excel.PrintOut(1, 5000, 1, False, 'Rumborak PDF-Writer Plus 1.0 RC5', \ True, False, tmpfile) Excel.Saved = 1 Excel.Close() myExcel.Quit() del Excel del myExcel os.popen('c:\\gs\\gs8.15\\bin\\gswin32c.exe -sDEVICE=pdfwrite -r300 -dNOPAUSE \ -dBATCH -dSAFER -sPAPERSIZE=a4 \ -sOutputFile="'+path_to_watch+filename+'.pdf" "'+tmpfile+'"') #os.remove(path_to_watch+filename) os.remove(tmpfile) pythoncom.CoUninitialize() while 1: time.sleep (0.1) after = dict ([(f, None) for f in os.listdir (path_to_watch)]) added = [f for f in after if not f in before] if added and added[0][-3:]=='xls': starttime = time.clock() print "File ", ", ".join (added), "added to queue" convert(added[0]) stoptime = time.clock() print "OK. It took", stoptime-starttime, 'seconds.\n' before = after
Automating Microsoft Outlook
For Outlook automation it is nesseccary to use the makepy utility. You do this either from the tools menu of the Pythonwin-Editor (installed with Pywin32 or ActivePython) or you call the file c:\python23\Lib\site-packages\win32com\client\makepy.py. You then have to select the Outlook Object Library (“Microsoft Outlook 10.0 Object Library” for Office 10.0 or known as Office XP).
After that Python generates cachefiles into the directory c:\python23\Lib\site-packages\win32com\gen_py or c:\temp\gen_py to tell Python more about the Outlook object library.
Here is a well known example which dumps all adressbook entries from your default adressbook:
import codecs, win32com.client # This example dumps the items in the default address book # needed for converting Unicode->Ansi (in local system codepage) DecodeUnicodeString = lambda x: codecs.latin_1_encode(x)[0] def DumpDefaultAddressBook(): # Create instance of Outlook o = win32com.client.Dispatch("Outlook.Application") mapi = o.GetNamespace("MAPI") folder = mapi.GetDefaultFolder(win32com.client.constants.olFolderContacts) print "The default address book contains",folder.Items.Count,"items" # see Outlook object model for more available properties on ContactItem objects attributes = [ 'FullName', 'Email1Address'] for i in range(1,folder.Items.Count+1): print "~~~ Entry %d ~~~" % i item = folder.Items[i] for attribute in attributes: print attribute, eval('item.%s' % attribute) o = None DumpDefaultAddressBook()
Automating Microsoft Powerpoint
One more example how to automate Microsoft Powerpoint and printout a
postscript file with a specified postscript printer (yes, more than one
printers can be installed on the system).
Multithreadding:
Unlike Word and Excel Powerpoint can not run in multiple instances.
If you want to use Powerpoint server based you must implement code to
handle the Powerpoint processes.
How to call the function:
You simply call the function with the name of the Word file, Postscript file and the printername which you want to use.:
e.g.:
make_ps.powerpoint(‘c:\test\powerpointfilename.ppt’, ‘c:\test\psfilename.ps’, ‘My Postscript Printername’)
The source code:
def powerpoint(powerpointfile, psfile, printer): pythoncom.CoInitializeEx(pythoncom.COINIT_APARTMENTTHREADED) myPowerpoint = win32com.client.DispatchEx('Powerpoint.Application') myPpt = myPowerpoint.Presentations.Open(powerpointfile, False, False, False) myPpt.PrintOptions.PrintInBackground = 0 myPpt.PrintOptions.ActivePrinter = printer myPpt.Saved = 1 myPpt.PrintOut(1, 5000, psfile, 0, False) myPpt.Close() #myPowerpoint.Quit() del myPpt #del myPowerpoint pythoncom.CoUninitialize()
Automating Microsoft Word
One small example how to automate Microsoft Word and printout a
postscript file with a specified postscript printer (yes, more than one
printers can be installed on the system).
Multithreadding:
Unlike
Powerpoint Microsoft Word can run in multiple instances – If a program
creates more Word processes you will see them in the task manager.
How to call the function:
You simply call the function with the name of the Word file, Postscript file and the printername which you want to use.:
eg.
make_ps.word(‘c:\test\wordfilename.doc’, ‘c:\test\psfilename.ps’, ‘My Postscript Printername’)
The source code:
import win32com.client, pythoncom, time def word(wordfile, psfile, printer): pythoncom.CoInitializeEx(pythoncom.COINIT_APARTMENTTHREADED) myWord = win32com.client.DispatchEx('Word.Application') myWord.Application.ActivePrinter = printer myDoc = myWord.Documents.Open(wordfile, False, False, False) myDoc.Saved=1 myWord.Application.NormalTemplate.Saved = 1 myWord.PrintOut(True, False, 0, psfile) while myWord.BackgroundPrintingStatus > 0: time.sleep(0.1) myDoc.Close() myWord.Quit() del myDoc del myWord pythoncom.CoUninitialize()
Submitting values and clicking buttons in IE
Submits data to a website and / or clicks on a specific button using COM.
# Use the makepy utility for the "Microsoft Internet Controls (1.1)" # object library to get early binding. from win32com.client import Dispatch from time import sleep ie = Dispatch("InternetExplorer.Application") #Create browser instance. ie.Visible = 1 # Make it visible (0 = invisible) ie.Navigate("http://www.google.com") while ie.ReadyState != 4: # Wait for browser to finish loading. sleep(1) doc = ie.Document # Get the document. while doc.readyState != "complete": # Wait for document to finish sleep(1) doc.f.q.value = "qwerty" # form name is 'f'; search field name is 'q' doc.f.submit() # Submits form using default button (in this case, btnG) # OR alternatively you can specify which button to click as follows... # doc.f.btnI.click() # click on button 'btnI' # Note: You can also reference the forms by the order in which they # appear in the forms collection. For example, you could use the # following code as well which references the first form. # doc.forms[0].q.value = 'qwerty'
Automating Microsoft Excel
One more example how to automate Microsoft Excel and printout a
postscript file with a specified postscript printer (yes more than one
printer can be installed on the system).
But unlike Word you can not check the background printing status in
Excel with the method "BackgroundPrintingStatus". This shouldn`t make
problems. I didn`t found an afvantage of this feature.
Multi-Threadding:
Unlike Powerpoint Excel works in more than one instances.
How to call the function:
You simply call the function with the name of the Word file, Postscript file and the printername which you want to use.:
The source code:
def excel(excelfile, psfile, printer): pythoncom.CoInitializeEx(pythoncom.COINIT_APARTMENTTHREADED) myExcel = win32com.client.DispatchEx('Excel.Application') myExcel.Application.AskToUpdateLinks = 0 Excel = myExcel.Workbooks.Open(excelfile, 0, False, 2) Excel.Saved = 1 Excel.PrintOut(1, 5000, 1, False, printer, True, False, psfile) Excel.Close() myExcel.Quit() del myExcel del Excel pythoncom.CoUninitialize() excel('c:/test/excelfilename.xls', 'c:/test/psfilename.ps', 'My Postscript Printername')