I've written previously about automating Microsoft PowerPoint with Ruby. Someone recently asked how to use Ruby code to insert hyperlinks into a PowerPoint slide. Let's take a look now at how this can be done.
Setting the Scene
Let's quickly review the code that will launch PowerPoint...
require 'win32ole'
ppt = WIN32OLE.new('PowerPoint.Application')
ppt.Visible = true
...create a new presentation...
doc = ppt.Presentations.Add()
...add a new slide...
slide = doc.Slides.Add(1, 2)
...and insert text into each of the two textboxes...
slide.Shapes(1).TextFrame.TextRange.Text = "Ruby on Windows"
slide.Shapes(2).TextFrame.TextRange.Text = "Ruby on Windows: PowerPoint"
To fully understand the above code, you may want to read this article, if you haven't already.
ActionSettings and HyperLinks
OK, now we have a PowerPoint presentation with a slide containing two textboxes, and we're ready to make the text of the second textbox a hyperlink. Let's grab a reference to the TextRange object that holds the text contained in the second textbox (a Shape object) on the slide:
text_range = slide.Shapes(2).TextFrame.TextRange
To define the action that is to be taken when a TextRange object is clicked, we need to work with the first item in the TextRange's ActionSettings collection:
action = text_range.ActionSettings(1)
This returns the ActionSetting object that represents a MouseClick action. This ActionSetting object includes a HyperLink object...
link = action.Hyperlink
...and it is the properties of this HyperLink object that we will modify to result in a link to our website:
link.Address = "http://rubyonwindows.blogspot.com/search/label/powerpoint"
link.ScreenTip = "Click to go to website"
link.TextToDisplay = "Ruby on Windows: PowerPoint"
Our complete code looks like this:
require 'win32ole'
ppt = WIN32OLE.new('PowerPoint.Application')
ppt.Visible = true
doc = ppt.Presentations.Add()
slide = doc.Slides.Add(1, 2)
slide.Shapes(1).TextFrame.TextRange.Text = "Ruby on Windows"
slide.Shapes(2).TextFrame.TextRange.Text = "Ruby on Windows: PowerPoint"
text_range = slide.Shapes(2).TextFrame.TextRange
action = text_range.ActionSettings(1)
link = action.Hyperlink
link.Address = "http://rubyonwindows.blogspot.com/search/label/powerpoint"
link.ScreenTip = "Click to go to website"
link.TextToDisplay = "Ruby on Windows: PowerPoint"
That's all for now, but feel free to post a comment here or send me email with questions, comments, or suggested topics.
Thanks for stopping by!
1 comment:
Is it book yet? :(
Post a Comment