4

We prepare the following python script to display pictures in word tables.

import matplotlib.pyplot as plt
import pylab 
import win32com.client as win32  
import os

# Skip picture making parts

#Generate word file
#Create and formating
wordapp = win32.Dispatch("Word.Application") #create a word application object

wordapp.Visible = 1 # hide the word application

doc=wordapp.Documents.Add() 

# create a new application

doc.PageSetup.RightMargin = 20

doc.PageSetup.LeftMargin = 20

doc.PageSetup.Orientation = 1

# a4 paper size: 595x842

doc.PageSetup.PageWidth = 595
doc.PageSetup.PageHeight = 842

header_range= doc.Sections(1).Headers(win32.constants.wdHeaderFooterPrimary).Range

header_range.ParagraphFormat.Alignment = win32.constants.wdAlignParagraphCenter

header_range.Font.Bold = True

header_range.Font.Size = 12

header_range.Text = ""
#Create and formating

#insert table
total_column = 3
total_row = len(compound_name)+1
rng = doc.Range(0,0)
rng.ParagraphFormat.Alignment = win32.constants.wdAlignParagraphCenter
table = doc.Tables.Add(rng,total_row, total_column)
table.Borders.Enable = True
if total_column > 1:
    table.Columns.DistributeWidth()
#table title
table.Cell(1,1).Range.InsertAfter("title1")
table.Cell(1,2).Range.InsertAfter("title2")
table.Cell(1,3).Range.InsertAfter("title3")
#collect image
frame_max_width= 167 # the maximum width of a picture
frame_max_height= 125 # the maximum height of a picture
#
for index, filename in enumerate(filenames): # loop through all the files and folders for adding pictures
 if os.path.isfile(os.path.join(os.path.abspath("."), filename)): # check whether the current object is a file or not
      if filename[len(filename)-3: len(filename)].upper() == 'PNG': # check whether the current object is a JPG file


                    cell_column= index % total_column + 1
                    cell_row = index / total_column + 2


                    cell_range= table.Cell(cell_row, cell_column).Range
                    cell_range.ParagraphFormat.LineSpacingRule = win32.constants.wdLineSpaceSingle
                    cell_range.ParagraphFormat.SpaceBefore = 0 
                    cell_range.ParagraphFormat.SpaceAfter = 3

        #this is where we are going to insert the images
                    current_pic = cell_range.InlineShapes.AddPicture(os.path.join(os.path.abspath("."), filename))


doc.SaveAs(os.path.join(os.path.abspath("."),"final.doc"))
doc.Close()

However, when running it, the following error will pop out due to this line

 header_range= doc.Sections(1).Headers(win32.constants.wdHeaderFooterPrimary).Range

Here is the error message:

Traceback (most recent call last):
  File "Drawing.py", line 99, in <module>
  header_range= doc.Sections(1).Headers(win32.constants.wdHeaderFooterPrimary).Range
  File "C:\Python27\Lib\site-packages\win32com\client\__init__.py", line 170, in __getattr__
   raise AttributeError(a)
  AttributeError: wdHeaderFooterPrimary

It looks to me there are something wrong with "wdHeaderFooterPrimary". So I just mute the following lines and run again.

#header_range= doc.Sections(1).Headers(win32.constants.wdHeaderFooterPrimary).Range

#header_range.ParagraphFormat.Alignment = win32.constants.wdAlignParagraphCenter

#header_range.Font.Bold = True

#header_range.Font.Size = 12

#header_range.Text = ""

Another error message will show up:

Traceback (most recent call last):
  File "C:Drawing.py", line 114, in <module>
    rng.ParagraphFormat.Alignment = win32.constants.wdAlignParagraphCenter
  File "C:\Python27\Lib\site-packages\win32com\client\__init__.py", line 170, in __getattr__
    raise AttributeError(a)
AttributeError: wdAlignParagraphCenter

I am running python 2.7.6 in 64 bit windows 7. The matplotlib.pyplot and pylab are installed. The win32com.client is 2.7.6 32 bit and build 219. The Office are 64 bits but the download site review says win32 32bit should work fine in office 64 bits/windows 7 64 bits (http://sourceforge.net/projects/pywin32/?source=navbar). May I know if any guru might have any comment/solution? Thanks!

Chubaka
  • 2,933
  • 7
  • 43
  • 58

1 Answers1

5

The constants are available only if static dispatching is available. The requires either using EnsureDispatch (instead of Dispatch) or generating the type library via makepy.py or genclient (which EnsureDispatch does for you). So I would try using the EnsureDispatch. Note: it is in win32com.client.gencache:

xl = win32com.client.gencache.EnsureDispatch ("Word.Application")
Oliver
  • 27,510
  • 9
  • 72
  • 103
  • Hi Schillii, thanks for your comment! When I try EnsureDispatch, the following error message will pop up: "Traceback (most recent call last): File "C:\Drawing.py", line 80, in wordapp = win32.EnsureDispatch("Word.Application") AttributeError: 'module' object has no attribute 'EnsureDispatch'" – Chubaka Jul 27 '14 at 18:51
  • Thanks @Schollii. This was the solution to my problem. – hugo24 Dec 03 '14 at 10:51
  • 1
    Thanks, this explains why it worked for me after I changed from using EnsureDispatch to Dispatch but wouldnt work on new machines. – Dean Feb 25 '16 at 16:29