[Tutor] Planning to write Python scripts and programs (migrating a Basic macro)

Lloyd Kvam pythontutor@venix.com
Fri, 18 Jan 2002 08:18:49 -0500


I second Danny's book recommendation.  Here is a snippet of code that we have been
using for creating a report in Word.  There's more, but it starts depending on other
classes that we've written, so it is harder to use anywhere.  As you can see from the
comment, the book includes enough sample code to get you productive very quickly.
(With WordReport, we started with the sample code and made modifications to fit our
needs.)

import win32com.client

class WordReport:
	""" Wrapper around Word 8 documents to make them easy to build.
		Has variables for the Applications, Document and Selection;
		most methods add things at the end of the document.
		Taken from 'Python Programming on Win32'
	"""
	def __init__(self, templatefile=None):
		self.wordApp = win32com.client.Dispatch('Word.Application')
		if templatefile == None:
			self.wordDoc = self.wordApp.Documents.Add()
		else:
			self.wordDoc = self.wordApp.Documents.Add(Template=templatefile)

		#set up the selection
		self.wordDoc.Range(0,0).Select()
		self.wordSel = self.wordApp.Selection

	def show(self):
		# convenience when debugging
		self.wordApp.ActiveWindow.View.Type = 3     # wdPageView
		self.wordApp.Visible = 1

	def getStyleList(self):
		# returns a dictionary of the styles in a document
		self.styles = []
		stylecount = self.wordDoc.Styles.Count
		for i in range(1, stylecount + 1):
			styleObject = self.wordDoc.Styles(i)
			self.styles.append(styleObject.NameLocal)

	def saveAs(self, filename):
		self.wordDoc.SaveAs(filename)

	def printout(self):
		self.wordDoc.PrintOut()

	def selectEnd(self):
		# ensures insertion point is at the end of the document
		self.wordSel.Collapse(0)
		# 0 is the constant wdCollapseEnd; don't want to depend
		# on makepy support.

	def selectBegin(self):
		# ensures insertion point is at the start of selection
		self.wordSel.Collapse()
		# default of Collapse() is start

	def addText(self, text, bookmark=None):
		if bookmark:
			self.wordDoc.Bookmarks(bookmark).Select()
			self.wordApp.Selection.TypeText(text)
		else:
			self.wordSel.InsertAfter(text)
		self.selectEnd()

	def addStyledPara(self, text, stylename):
		if text[-1] <> '\n':
			text = text + '\n'
		self.wordSel.InsertAfter(text)
		self.wordSel.Style = stylename
		self.selectEnd()


Danny Yoo wrote:

> On Wed, 16 Jan 2002, McCarney, James Alexander wrote:
> 
> 
>>I have a Word (Basic) macro that I run against images in docs that I
>>create to resize them.  I wonder if I could either rewrite it totally
>>in Py or have Py open the document file, execute the macro, save the
>>file, and quit.
>>
> 
> Hi James,
> 
> Yes, it's possible to do this.  You may want to look at the book "Python
> and Win32 Programming", by Mark Hammond:
> 
>     http://www.oreilly.com/catalog/pythonwin32/
> 
> I don't have the book with me, but I think the book does cover examples of
> making Word dance around with Python.  If you're a Windows user, and you
> want to use Python to fiddle around with Windows itself, the book is a
> must buy.
> 
> 
> 
>>The Basic code is this (shield your eyes or snip it out now, cos it's
>>not Py!!!)
>>
> 
> Don't worry about it; I think we can handle it.  *grin*
> 
> 
> 
>>Sub ReduceTo50()
>>'
>>' ReduceTo50 Macro
>>' Macro created 09/12/01 by James Alexander McCarney
>>'
>>Dim lngX As Long
>>On Error Resume Next 'Important or the code may puke
>>
>>For lngX = 1 To ActiveDocument.InlineShapes.Count
>>    ActiveDocument.InlineShapes(lngX).Select
>>    If (ActiveDocument.InlineShapes(lngX).Type = wdInlineShapeLinkedPicture
>>Or ActiveDocument.InlineShapes(lngX).Type = wdInlineShapePicture) Then
>>        Selection.InlineShapes(1).ScaleHeight = 40  'Set the height to
>>whatever you want 50, 40, 30 (for smaller pix)
>>        Selection.InlineShapes(1).ScaleWidth = 40   'Set the height to
>>whatever you want 50, 40, 30 (for smaller pix)
>>
>>    End If
>>
>>Next lngX
>>
>>End Sub
>>
> 
> Hey, that didn't look too bad at all.  Wow, BASIC has changed.  *grin*
> 
> 
> I think this function should translate pretty well to Python, but I don't
> know well enought the kind of objects we can fool around with.  Oh well,
> I'll try guessing.  Here's a very buggy translation --- I'm positive that
> it won't work --- but it might help you get started:
> 
> ###
> def ReduceTo50():
>     """
>     ReduceTo50 Macro
>     Macro created 09/12/01 by James Alexander McCarney
>     """
>     for i in range(1, ActiveDocument.InlineShapes.Count):
>         try:
>             shape = ActiveDocument.InlineShapes(i)
>             shape.Select()
>             if shape.Type in (wdInlineShapeLinedPicture, 
>                               wdInlineShapePicture):
>                 selection.InlineShapes(1).ScaleHeight = 40
>                 selection.InLineShapes(1).ScaleWidth = 40
>         except Exception, e:
>             ## Do we want to pass errors silently?  Maybe
>             ## we should say something to the user to warn them.
>             ## For now, let's just pass it.
>             pass
> ###
> 
> Since it looks like you're doing a lot of Windows specific stuff, you'll
> definitely want to get in contact with the python-win32 mailing list, so
> that you can also ask for their expertise too.  You can find them here:
> 
>     http://mail.python.org/mailman/listinfo/python-win32
> 
> 
> Best of wishes to you.  Tell us your progress on this; it sounds really
> interesting!
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 


-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice: 
603-443-6155
fax: 
801-459-9582