1

Sorry for my bad English.

I'm trying to substitute a string in .docx file by a .jpg file. First I convert JPEG to BMP and move it to clipboard follow Copy PIL/PILLOW Image to Windows Clipboard, then use Find.Execute with "^c" to substitute a special string in docx file.

The substitution works well, but it paste a image with width of 15.42cm to the .docx file. I've tried to resize it with im.resize, but it ends with a large blur image rather than a small one. How could I make it smaller?

I'm using python2.7.2 and Win7. Thanks a lot.

from win32com.client import Dispatch
from cStringIO import StringIO
import win32clipboard
import win32com
from PIL import Image

def setImageToClipboard(clip_type, data):
    win32clipboard.OpenClipboard()
    win32clipboard.EmptyClipboard()
    win32clipboard.SetClipboardData(clip_type, data)
    win32clipboard.CloseClipboard()

filepath = 'd:/tmp.jpg'
im = Image.open(filepath)
#im = im.resize((10, 10))

output = StringIO()
im.convert("RGB").save(output, "BMP")
data = output.getvalue()[14:]
output.close()

w = win32com.client.Dispatch('Word.Application')
w.Visible = 1
w.DisplayAlerts = 0
doc = w.Documents.Open("d:/clipboard_test.docx")

search = "TEST"

setImageToClipboard(win32clipboard.CF_DIB, data)
w.Selection.Find.ClearFormatting()
w.Selection.Find.Replacement.ClearFormatting()
w.Selection.Find.Execute("TEST", False, True, False, False, False, True, 1, True, ReplaceWith="^c", Replace=2000)

doc.SaveAs("d:/clipboard_test2.docx")
doc.Close()
w.Quit() 
sKaelthas
  • 13
  • 3

1 Answers1

0

You can do this much more cleanly and without actually needing MS-Word installed or starting it up by using python-docx.

You will need to read in your existing document, find the text that you need to replace and then use document.add_picture('monty-truth.png', width=Inches(1.25)) rather than using word and pretending to paint.

The only other option is to have python select the image that you have pasted and set its properties within word.

Steve Barnes
  • 27,618
  • 6
  • 63
  • 73