views:

727

answers:

2

I am trying to insert an image (jpg) in to a word document and the Selection.InlineShapes.AddPicture does not seem to be supported by win32old or I am doing something wrong. Has anyone had any luck inserting images.

+1  A: 

Running on WinXP, Ruby 1.8.6, Word 2002/XP SP3, I recorded macros and translated them, as far as I could understand them, into this:

require 'win32ole'

begin
  word = WIN32OLE::new('Word.Application')   # create winole Object
  doc = word.Documents.Add
  word.Selection.InlineShapes.AddPicture "C:\\pictures\\some_picture.jpg", false, true
  word.ChangeFileOpenDirectory "C:\\docs\\"
  doc.SaveAs "doc_with_pic.doc"
  word.Quit
rescue Exception => e
  puts e
  word.Quit
ensure
  word.Quit unless word.nil?
end

It seems to work. Any use?

Mike Woodhouse
A: 

You can do this by calling the Document.InlineShapes.AddPicture() method.

The following example inserts an image into the active document, before the second sentence.

    require 'win32ole'

    word = WIN32OLE.connect('Word.Application')
    doc = word.ActiveDocument

    image = 'C:\MyImage.jpg'
    range = doc.Sentences(2)

    params = { 'FileName' => image, 'LinkToFile' => false, 
               'SaveWithDocument' => true, 'Range' => range }

    pic = doc.InlineShapes.AddPicture( params )

Documentation on the AddPicture() method can be found here.

Additional details on automating Word with Ruby can be found here.

This is the answer by David Mullet and can be found here

Webbisshh