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()

Speech recognition

# Inigo Surguy (inigosurguy at hotmail.com)
# Sample code for speech recognition using the MS Speech API
from win32com.client import constants
import win32com.client
import pythoncom

"""Sample code for using the Microsoft Speech SDK 5.1 via COM in Python.
    Requires that the SDK be installed (it's a free download from
            http://www.microsoft.com/speech
    and that MakePy has been used on it (in PythonWin,
    select Tools | COM MakePy Utility | Microsoft Speech Object Library 5.1).

    After running this, then saying "One", "Two", "Three" or "Four" should
    display "You said One" etc on the console. The recognition can be a bit
    shaky at first until you've trained it (via the Speech entry in the Windows
    Control Panel."""

class SpeechRecognition:
    """ Initialize the speech recognition with the passed in list of words """
    def __init__(self, wordsToAdd):
        # For text-to-speech
        self.speaker = win32com.client.Dispatch("SAPI.SpVoice")
        # For speech recognition - first create a listener
        self.listener = win32com.client.Dispatch("SAPI.SpSharedRecognizer")
        # Then a recognition context
        self.context = self.listener.CreateRecoContext()
        # which has an associated grammar
        self.grammar = self.context.CreateGrammar()
        # Do not allow free word recognition - only command and control
        # recognizing the words in the grammar only
        self.grammar.DictationSetState(0)
        # Create a new rule for the grammar, that is top level (so it begins
        # a recognition) and dynamic (ie we can change it at runtime)
        self.wordsRule = self.grammar.Rules.Add("wordsRule",
                        constants.SRATopLevel + constants.SRADynamic, 0)
        # Clear the rule (not necessary first time, but if we're changing it
        # dynamically then it's useful)
        self.wordsRule.Clear()
        # And go through the list of words, adding each to the rule
        [ self.wordsRule.InitialState.AddWordTransition(None, word) for word in wordsToAdd ]
        # Set the wordsRule to be active
        self.grammar.Rules.Commit()
        self.grammar.CmdSetRuleState("wordsRule", 1)
        # Commit the changes to the grammar
        self.grammar.Rules.Commit()
        # And add an event handler that's called back when recognition occurs
        self.eventHandler = ContextEvents(self.context)
        # Announce we've started
        self.say("Started successfully")
    """Speak a word or phrase"""
    def say(self, phrase):
        self.speaker.Speak(phrase)


"""The callback class that handles the events raised by the speech object.
    See "Automation | SpSharedRecoContext (Events)" in the MS Speech SDK
    online help for documentation of the other events supported. """
class ContextEvents(win32com.client.getevents("SAPI.SpSharedRecoContext")):
    """Called when a word/phrase is successfully recognized  -
        ie it is found in a currently open grammar with a sufficiently high
        confidence"""
    def OnRecognition(self, StreamNumber, StreamPosition, RecognitionType, Result):
        newResult = win32com.client.Dispatch(Result)
        print "You said: ",newResult.PhraseInfo.GetText()
    
if __name__=='__main__':
    wordsToAdd = [ "One", "Two", "Three", "Four" ]
    speechReco = SpeechRecognition(wordsToAdd)
    while 1:
        pythoncom.PumpWaitingMessages()


Manipulate Data in Lotus Notes

I didn`t test this example. But it shows how to manipulate data in Lotus notes with Python/Pywin32:

import win32com.client
import win32com.client
sess=win32com.client.Dispatch("Lotus.NotesSession")

db=sess.GetDatabase("","log.nsf")
print db.Title

Automating Windows Media Player

I found this Windows Media Player example on a website:

You can automate  Microsoft Media Player with win32com without
starting the GUI.This example opens and plays some media files:

# this program will play MP3, WMA, MID, WAV files via the WindowsMediaPlayer
from win32com.client import Dispatch
mp = Dispatch("WMPlayer.OCX")
# use an mp3 file you have ...
#tune = mp.newMedia("C:/Program Files/Common Files/HP/Memories Disc/2.0/audio/Swing.mp3")
# or copy one to the working folder ...
#tune = mp.newMedia("Bier1.mp3")

# you can also play wma files, this cool sound came with XP ...
tune = mp.newMedia("C:/WINDOWS/system32/oobe/images/title.wma")
mp.currentPlaylist.appendItem(tune)
mp.controls.play()
# to stop playing use
raw_input("Press Enter to stop playing")

mp.controls.stop()

Grab text or source from HTML pages

import win32com.client
from time import sleep

def download_url_with_ie(url):
    """
    Given a url, it starts IE, loads the page, gets the HTML.
    Works only in Win32 with Python Win32com extensions enabled.
    Needs IE. Why? If you’re forced to work with Brain-dead 
    closed sourceapplications that go to tremendous length to deliver
    output specific to browsers; and the application has no interface
    other than a browser; and you want get data into a CSV or XML
    for further analysis;
    Note: IE internally formats all HTML to stupid mixed-case, no-
    quotes-around-attributes syntax. So if you are planning to parse
    the data, make sure you study the output of this function rather
    than looking at View-source alone.
    """

    #if you are calling this function in a loop, it is more
    #efficient to open ie once at the beginning, outside this
    #function and then use the same instance to go to url’s
    ie = win32com.client.Dispatch("InternetExplorer.Application")

    ie.Visible = 1 #make this 0, if you want to hide IE window
    #IE started
    ie.Navigate(url)
    #it takes a little while for page to load. sometimes takes 5 sec.
    if ie.Busy:
        sleep(5)
    #now, we got the page loaded and DOM is filled up
    #so get the text
    text = ie.Document.body.innerHTML
    #text is in unicode, so get it into a string
    text = unicode(text)
    text = text.encode('ascii','ignore')
    #save some memory by quitting IE! **very important** 
    ie.Quit()
    #return text
    print text
download_url_with_ie('http://www.goermezer.de')

Read from a Microsoft Access database with ADODB

This example demonstrates how to read from a Microsoft Access database
via AdoDB and Python/Pywin32. This code opens a test database and
prints the names of the columns.

import win32com.client

connection = win32com.client.Dispatch(r'ADODB.Connection')
DSN = 'PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA SOURCE=c:\\pfad\\testdb.mdb;'
connection.Open(DSN)
recordset = win32com.client.Dispatch(r'ADODB.Recordset')
recordset.Open('SELECT * FROM Auftraege', connection, 1, 3)
fields_dict = {}
for x in range(recordset.Fields.Count):
    fields_dict[x] = recordset.Fields.Item(x).Name
    print fields_dict[x], recordset.Fields.Item(x).Value

Calculator automation via sendkeys

This example opens the Windows calculator (calc) and makes some input like using the keyboard.

import win32com.client
import win32api

shell = win32com.client.Dispatch("WScript.Shell")
shell.Run("calc")
win32api.Sleep(100)
shell.AppActivate("Calculator")
win32api.Sleep(100)
shell.SendKeys("1{+}")
win32api.Sleep(500)
shell.SendKeys("2")
win32api.Sleep(500)
shell.SendKeys("~") # ~ is the same as {ENTER}
win32api.Sleep(500)
shell.SendKeys("*3")
win32api.Sleep(500)
shell.SendKeys("~")
win32api.Sleep(2500)

Controlling applications via sendkeys

With sendkeys (Python/Pywin32 uses WScript from Windows Scripting Host) one can control applications via shortcuts. eg.

This example first opens Microsoft Outlook, takes the first element, marks the full text and takes it into the clipboard (CTRL + C).

import win32com.client
shell = win32com.client.Dispatch("WScript.Shell")
shell.Run("outlook")
shell.AppActivate("Outlook")
shell.SendKeys("^o", 0) # 1 für Pause = true 0 für nein
shell.SendKeys("^a", 0)
shell.SendKeys("^c", 0)

Here is a list of WScript-commands:

Key Argument
BACKSPACE {BACKSPACE}, {BS}, or {BKSP}
BREAK {BREAK}
CAPS LOCK {CAPSLOCK}
DEL or DELETE {DELETE} or {DEL}
DOWN ARROW {DOWN}
END {END}
ENTER {ENTER} or ~
ESC {ESC}
HELP {HELP}
HOME {HOME}
INS or INSERT {INSERT} or {INS}
LEFT ARROW {LEFT}
NUM LOCK {NUMLOCK}
PAGE DOWN {PGDN}
PAGE UP {PGUP}
PRINT SCREEN {PRTSC}
RIGHT ARROW {RIGHT}
SCROLL LOCK {SCROLLLOCK}
TAB {TAB}
UP ARROW {UP}
F1 {F1}
F2 {F2}
F3 {F3}
F4 {F4}
F5 {F5}
F6 {F6}
F7 {F7}
F8 {F8}
F9 {F9}
F10 {F10}
F11 {F11}
F12 {F12}
F13 {F13}
F14 {F14}
F15 {F15}
F16 {F16}

Steuerung, Shift, ALT und Enter werden wie folgt gesendet:

 

Key Special Character
SHIFT +
CTRL ^
ALT %
ENTER ~

The documentation of Sendkeys you can find at Microsoft.

Show usable ProgIDs for win32com

This example shows you the available ProgIDs of the Windows applications which are installed and ahould be usable  with win32com. My problem is, that most of the ProgIDs are shown, but not all ?!

import win32com.client
strComputer = "."
objWMIService = win32com.client.Dispatch("WbemScripting.SWbemLocator")
objSWbemServices = objWMIService.ConnectServer(strComputer,"root\cimv2")
colItems = objSWbemServices.ExecQuery("Select * from Win32_ProgIDSpecification")
for objItem in colItems:
    print "Caption: ", objItem.Caption
    print "Check ID: ", objItem.CheckID
    print "Check Mode: ", objItem.CheckMode
    print "Description: ", objItem.Description
    print "Name: ", objItem.Name
    print "Parent: ", objItem.Parent
    print "ProgID: ", objItem.ProgID
    print "Software Element ID: ", objItem.SoftwareElementID
    print "Software Element State: ", objItem.SoftwareElementState
    print "Target Operating System: ", objItem.TargetOperatingSystem
    print "Version: ", objItem.Version
    print "-------------------------------------------------------------------\n"

Shellwindows

This example prints the name and and pathes of the open windows (Tip: You can get the CLSID with makepy in Pythonwin):

import win32com.client
# look in the makepy output for IE for the 'CLSIDToClassMap'
# dictionary, and find the entry for 'ShellWindows'
clsid='{9BA05972-F6A8-11CF-A442-00A0C90A8F39}'
ShellWindows=win32com.client.Dispatch(clsid)
for i in range(ShellWindows.Count):
    print i
    # this is the titlebar value
    print ShellWindows[i].LocationName
    # this is the current URL
    print ShellWindows[i].LocationURL
print