|
Package parasol ::
Module Word_wrapper
|
|
1 import win32com
2 from win32com.client import Dispatch
3 import string
4
5
6 wdNormalView =0x1
7 wdStyleTypeTable =0x3
8 wdAutoFitContent =0x1
9 wdAutoFitFixed =0x0
10 wdAutoFitWindow =0x2
11 wdWord8TableBehavior =0x0
12 wdWord9TableBehavior =0x1
13
14 wdAlignRowCenter =0x1
15 wdAlignRowLeft =0x0
16 wdAlignRowRight =0x2
17
18 justDict = {'c':wdAlignRowCenter, 'l':wdAlignRowLeft, 'r':wdAlignRowRight }
19
20 wdLineStyleNone =0x0
21 wdBorderBottom =-3
22 wdBorderDiagonalDown =-7
23 wdBorderDiagonalUp =-8
24 wdBorderHorizontal =-5
25 wdBorderLeft =-2
26 wdBorderRight =-4
27 wdBorderTop =-1
28 wdBorderVertical =-6
29
30
31 wdAuto =0x0
32 wdBlack =0x1
33 wdBlue =0x2
34 wdBrightGreen =0x4
35 wdByAuthor =-1
36 wdDarkBlue =0x9
37 wdDarkRed =0xd
38 wdDarkYellow =0xe
39 wdGray25 =0x10
40 wdGray50 =0xf
41 wdGreen =0xb
42 wdNoHighlight =0x0
43 wdPink =0x5
44 wdRed =0x6
45 wdTeal =0xa
46 wdTurquoise =0x3
47 wdViolet =0xc
48 wdWhite =0x8
49 wdYellow =0x7
50
51 textColorIndexDict = {'auto':wdAuto ,'k':wdBlack ,'b':wdBlue ,'gg':wdBrightGreen ,
52 'auth':wdByAuthor ,'bb':wdDarkBlue ,'rr':wdDarkRed ,'yy':wdDarkYellow ,
53 '25':wdGray25 ,'50':wdGray50 ,'g':wdGreen ,'no':wdNoHighlight ,'p':wdPink ,
54 'r':wdRed ,'t':wdTeal ,'q':wdTurquoise ,'v':wdViolet ,'w':wdWhite ,
55 'y':wdYellow }
56
57
58 if 1:
59 wdColorAqua =0xcccc33
60 wdColorAutomatic =-16777216
61 wdColorBlack =0x0
62 wdColorBlue =0xff0000
63 wdColorBlueGray =0x996666
64 wdColorBrightGreen =0xff00
65 wdColorBrown =0x3399
66 wdColorDarkBlue =0x800000
67 wdColorDarkGreen =0x3300
68 wdColorDarkRed =0x80
69 wdColorDarkTeal =0x663300
70 wdColorDarkYellow =0x8080
71 wdColorGold =0xccff
72 wdColorGray05 =0xf3f3f3
73 wdColorGray10 =0xe6e6e6
74 wdColorGray125 =0xe0e0e0
75 wdColorGray15 =0xd9d9d9
76 wdColorGray20 =0xcccccc
77 wdColorGray25 =0xc0c0c0
78 wdColorGray30 =0xb3b3b3
79 wdColorGray35 =0xa6a6a6
80 wdColorGray375 =0xa0a0a0
81 wdColorGray40 =0x999999
82 wdColorGray45 =0x8c8c8c
83 wdColorGray50 =0x808080
84 wdColorGray55 =0x737373
85 wdColorGray60 =0x666666
86 wdColorGray625 =0x606060
87 wdColorGray65 =0x595959
88 wdColorGray70 =0x4c4c4c
89 wdColorGray75 =0x404040
90 wdColorGray80 =0x333333
91 wdColorGray85 =0x262626
92 wdColorGray875 =0x202020
93 wdColorGray90 =0x191919
94 wdColorGray95 =0xc0c0c
95 wdColorGreen =0x8000
96 wdColorIndigo =0x993333
97 wdColorLavender =0xff99cc
98 wdColorLightBlue =0xff6633
99 wdColorLightGreen =0xccffcc
100 wdColorLightOrange =0x99ff
101 wdColorLightTurquoise =0xffffcc
102 wdColorLightYellow =0x99ffff
103 wdColorLime =0xcc99
104 wdColorOliveGreen =0x3333
105 wdColorOrange =0x66ff
106 wdColorPaleBlue =0xffcc99
107 wdColorPink =0xff00ff
108 wdColorPlum =0x663399
109 wdColorRed =0xff
110 wdColorRose =0xcc99ff
111 wdColorSeaGreen =0x669933
112 wdColorSkyBlue =0xffcc00
113 wdColorTan =0x99ccff
114 wdColorTeal =0x808000
115 wdColorTurquoise =0xffff00
116 wdColorViolet =0x800080
117 wdColorWhite =0xffffff
118 wdColorYellow =0xffff
119
120
121 colorDict = {'a':wdColorAqua , 'auto':wdColorAutomatic , 'k':wdColorBlack , 'b':wdColorBlue ,
122 'bg':wdColorBlueGray , 'gg':wdColorBrightGreen ,
123 'brn':wdColorBrown , 'db':wdColorDarkBlue ,
124 'dg':wdColorDarkGreen , 'dr':wdColorDarkRed ,
125 'dt':wdColorDarkTeal , 'dy':wdColorDarkYellow ,
126 'gold':wdColorGold , '05':wdColorGray05 , '10':wdColorGray10 , '125':wdColorGray125 ,
127 '15':wdColorGray15 , '20':wdColorGray20 , '25':wdColorGray25 , '30':wdColorGray30 ,
128 '35':wdColorGray35 , '375':wdColorGray375 , '40':wdColorGray40 , '45':wdColorGray45 ,
129 '50':wdColorGray50 , '55':wdColorGray55 , '60':wdColorGray60 , '625':wdColorGray625 ,
130 '65':wdColorGray65 , '70':wdColorGray70 , '75':wdColorGray75 , '80':wdColorGray80 ,
131 '85':wdColorGray85 , '875':wdColorGray875 , '90':wdColorGray90 , '95':wdColorGray95 ,
132 'g':wdColorGreen , 'i':wdColorIndigo , 'l':wdColorLavender , 'lb':wdColorLightBlue ,
133 'lg':wdColorLightGreen , 'lo':wdColorLightOrange ,
134 'lt':wdColorLightTurquoise , 'ly':wdColorLightYellow ,
135 'lime':wdColorLime , 'olive':wdColorOliveGreen ,
136 'o':wdColorOrange , 'pb':wdColorPaleBlue ,
137 'p':wdColorPink , 'plum':wdColorPlum ,
138 'r':wdColorRed , 'rose':wdColorRose , 'sea':wdColorSeaGreen ,
139 'sky':wdColorSkyBlue , 'tan':wdColorTan , 't':wdColorTeal , 'q':wdColorTurquoise ,
140 'v':wdColorViolet , 'w':wdColorWhite , 'y':wdColorYellow }
141
142
144 """Wrapper around Word documents to make them easy to build.
145 Has variables for the Applications, Document and Selection;
146 most methods add things at the end of the document"""
148 self.wordApp = Dispatch('Word.Application')
149 if templatefile == None:
150 self.wordDoc = self.wordApp.Documents.Add()
151 else:
152 self.wordDoc = self.wordApp.Documents.Add( Template=templatefile)
153
154 self.wordDoc.Range(0,0).Select()
155 self.wordSel = self.wordApp.Selection
156
157
158
160
161 self.wordApp.Visible = 1
162
164 self.wordApp.Visible = 1
165 self.wordApp.Windows(1).View.Type = wdNormalView
166 self.wordApp.Options.Pagination = False
167
168
170 self.wordApp.Visible = 0
171 self.wordApp.Windows(1).View.Type = wdNormalView
172 self.wordApp.Options.Pagination = False
173 self.wordApp.ScreenUpdating = False
174
175
177 self.wordDoc.SaveAs(filename)
178
181
183
184 wdDoNotSaveChanges =0x0
185 self.wordApp.Quit(wdDoNotSaveChanges)
186
188 self.wordDoc.PrintOut()
189
191 '''changes selection by NChar characters at Start'''
192 pbTextUnitCharacter = 1
193 self.wordSel.MoveStart( pbTextUnitCharacter, NChar )
194
196 '''changes selection by NChar characters at End'''
197 pbTextUnitCharacter = 1
198 self.wordSel.MoveEnd( pbTextUnitCharacter, NChar )
199
200
202
203 self.wordSel.Collapse(0)
204
205
206
207 - def addText(self, text):
208 R = self.wordSel.InsertAfter(text)
209 self.selectEnd()
210
211
212 - def addSelectedText(self, text):
213 R = self.wordSel.InsertBefore(text)
214
215
216
217 '''
218 Insert a paragraph in a named style
219 Fast, versatile, and lets graphic designers set the styles in Word.
220 >>> from win32com.client import constants
221 >>> mySelection.Style = constants.wdStyleHeading1
222 >>>
223 However, (a) this is limited to the built-in styles, and
224 (b) won't work without MakePy.
225 Our solution: get a style list back at run time, and use it to add them by name:
226
227 '''
229
230 self.styles = []
231 stylecount = self.wordDoc.Styles.Count
232 for i in range(1, stylecount + 1):
233 styleObject = self.wordDoc.Styles(i)
234 self.styles.append(styleObject.NameLocal)
235
237 if text[-1] <> '\n':
238 text = text + '\n'
239 self.wordSel.InsertAfter(text)
240 self.wordSel.Style = stylename
241
242 - def addTable(self, tableList, styleid=None, Range=None, fullWidth=0):
243
244
245
246
247
248 if Range==None:
249 Range = self.selectCharacter( -1 )
250
251 textlines = []
252 NRows = len( tableList )
253 NCols = 1
254 for row in tableList:
255 if len(row)>NCols:
256 NCols = len(row)
257
258
259
260 if fullWidth:
261 autofit = wdAutoFitWindow
262 else:
263 autofit = wdAutoFitContent
264 Tbl = self.wordDoc.Tables.Add( Range, NRows, NCols, wdWord9TableBehavior, autofit)
265
266
267
268 NR = 1
269 for row in tableList:
270 NC = 1
271 for s in row:
272 Tbl.Cell(NR, NC).Range.Text = str( s )
273 NC += 1
274 NR += 1
275
276
277 if styleid:
278 Tbl.AutoFormat(Format=styleid)
279
280 Tbl.AllowPageBreaks = False
281 return Tbl
282
283 - def createTableStyle(self, name='myStyle', font='Arial',
284 color='', bgcolor='',
285 size=14, borders=1, bold=0, keepTogether=1):
327
328
329 - def addCellText(self, Table=None, row=1, col=1, text=''):
330 if Table==None:
331 return
332
333 Table.Cell(row, col).Range.Text = str( text )
334
336 if Table==None or StyleName==None:
337 return
338
339 for i in range(1, Table.Rows.Count+1):
340 for j in range(1, Table.Columns.Count+1):
341 try:
342 Table.Cell(i,j).Range.Style = StyleName
343 except:
344 pass
345
346 - def setCellStyle(self, Table=None, row=1, col=1, text='',
347 StyleName='', fontName='', fontSize=0, just='', bold=None,
348 color='', bgcolor='', width=0):
349 if Table==None:
350 return
351
352 if row<1: row=1
353 if row>Table.Rows.Count: row=Table.Rows.Count
354 if col<1: col=1
355 if col>Table.Columns.Count: col=Table.Columns.Count
356
357 if len(text)>0:
358 try:
359 Table.Cell(row, col).Range.Text = str( text )
360 except:
361 pass
362
363 if len(StyleName)>0:
364 try:
365 Table.Cell(row,col).Range.Style = StyleName
366 except:
367 pass
368
369 if len(fontName)>0:
370 try:
371 Table.Cell(row,col).Range.Font.Name = fontName
372 except:
373 pass
374
375 if fontSize>0:
376 try:
377 Table.Cell(row,col).Range.Font.Size = fontSize
378 except:
379 pass
380
381 if len(just)>0:
382 try:
383 Table.Cell(row,col).Range.ParagraphFormat.Alignment = justDict[just]
384 except:
385 pass
386
387 if bold != None:
388 try:
389 Table.Cell(row,col).Range.Font.Bold = bold
390 except:
391 pass
392
393 if len(color)>0:
394 try:
395 Table.Cell(row,col).Range.Font.Color = colorDict[color]
396 except:
397 pass
398
399 if len(bgcolor)>0:
400 try:
401 Table.Cell(row,col).Range.Shading.BackgroundPatternColor = colorDict[bgcolor]
402 except:
403 pass
404
405 if width>0:
406 try:
407 Table.Cell(row,col).Width=width
408 except:
409 pass
410
411 - def mergeRow(self, Table=None, NRow=1):
412 if Table==None:
413 return
414
415 myrow = Table.Rows(NRow)
416 myrow.Cells.Merge()
417
418 '''Adding Charts and Images
419 Let's assume we've set up and saved an
420 Excel sheet with the right chart in it already.
421 '''
424
425
426
427 shape = self.wordDoc.InlineShapes.AddOLEObject(
428 ClassType='Excel.Chart',
429 FileName=filename
430 )
431
432 shape.Height = height
433 shape.Width = width
434
435
436 shape.Range.Cut()
437 self.wordSel.InsertAfter('chart will replace this')
438 self.wordSel.Range.Paste()
439 self.addStyledPara(caption, 'Normal')
440
441 - def addImage(self, filename, Range=None, fracPage=0.5):
442
443 hw=self.wordDoc.InlineShapes
444 if Range==None:
445 Image = hw.AddPicture(filename)
446 else:
447
448 print "Range provided for image add"
449 Image = hw.AddPicture(filename, False, True, Range)
450
451 PageW = self.wordDoc.PageSetup.PageWidth
452 desiredW = int( fracPage * PageW )
453 if Image.Width > desiredW:
454 ratio = float( desiredW ) / Image.Width
455 Image.Width = int( ratio * Image.Width )
456 Image.Height = int( ratio * Image.Height )
457
458 return Image
459
461
462 Ps = self.wordDoc.Paragraphs
463 if N<0:
464 N = Ps.Count + N + 1
465 if N<1: N=1
466 if N>Ps.Count: N = Ps.Count
467
468 RN = Ps(N).Range
469 RN.Select()
470 return RN
471
473
474 Ss = self.wordDoc.Sentences
475 if N<0:
476 N = Ss.Count + N + 1
477 if N<1: N=1
478 if N>Ss.Count: N = Ss.Count
479
480 RN = self.wordDoc.Range( Ss(N).Start, Ss(N).End)
481 RN.Select()
482 return RN
483
485
486 Ws = self.wordDoc.Words
487 if N<0:
488 N = Ws.Count + N + 1
489 if N<1: N=1
490 if N>Ws.Count: N = Ws.Count
491
492 RN = self.wordDoc.Range( Ws(N).Start, Ws(N).End)
493 RN.Select()
494 return RN
495
497 Cs = self.wordDoc.Characters
498 if N<0:
499 N = Cs.Count + N + 1
500 if N<1: N=1
501 if N>Cs.Count: N = Cs.Count
502
503 RN = self.wordDoc.Range( Cs(N).Start, Cs(N).End)
504 RN.Select()
505 return RN
506
507 if __name__ == "__main__":
508
509 w = WordWrap()
510 w.show()
511
512
513
514
515
516
517 from Summary import Summary
518 S = Summary( summaryTitle='Summary Title', subTitle='subtitle')
519 S.addAssumption( 'Assume this is a test' )
520
521 S.addInput( label='Solar Flux', value=1.0, units='BTU/sqin', format='%g')
522 S.addOutput(label='Tea Temperature', value=100.0, units='C', format='%g')
523
524 summ = S
525 sel = w.selectCharacter(1)
526
527 w.changeEndSelection( -1 )
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544 tableStr = [('',),('',),('',),('','')]
545 wordTable1 = w.addTable( tableStr )
546 w.mergeRow( Table=wordTable1, NRow=1)
547 w.mergeRow( Table=wordTable1, NRow=2)
548
549 w.addCellText(wordTable1, row=2, col=1, text='\n'.join(summ.getSummTopLines()))
550 w.addCellText(wordTable1, row=3, col=1, text='\n'.join(summ.getSummAssumptions()))
551
552 w.addCellText(wordTable1, row=4, col=1, text='\n'.join(summ.getSummInputs()))
553 w.addCellText(wordTable1, row=4, col=2, text='\n'.join(summ.getSummOutputs()))
554
555
556 w.wordDoc.Styles("Endnote Reference").Font.Size = 14
557 w.wordDoc.Styles("Endnote Reference").Font.Name = "Courier New"
558 w.setAllTableCellStyle( Table=wordTable1, StyleName="Endnote Reference")
559 wordTable1.AutoFormat( Format=1 )
560
561
562
563
564 '''Dim MyPic As Shape 'or InlineShape
565
566 Set MyPic = ActiveDocument.InlineShapes.AddPicture(strPathToPicture)
567
568 With MyPic
569 .RelativeVerticalPosition = wdRelativeVerticalPositionPage
570 .Left = CentimetersToPoints(0)
571 .Top = wdShapeBottom
572 End With'''
573 if 0:
574 w.getStyleList()
575 print w.styles
576
577 keyInp = raw_input(" Hit Key to Close Word")
578 w.abandonWord()
579