Working with slide contents
Building presentations full of blank slides is straightforward. The next step is to add text and shapes to your slides. Any object on a slide, whether it is a picture, a title, text, shape, an OLE object, or something else, becomes one object in the Shapes collection. On the surface, this seems like an odd way to design a collection, as many different kinds of items obviously require different sets of properties. Looking a bit deeper, if you see each of those objects as something that takes up height and width, at a certain position, and contains a certain type of content, with text optional, then each of these strange objects starts to look as if it could belong to the same collection.
As in most COM collections, you can refer to a particular Shape object using its index in the collection (like oSlide.Shapes[7]) or its name (oSlide.Shapes["Rectangle 2"]).
The shape s name is generated when it is added to the slide. The default naming convention is the shape type keyword, followed by a number representing the number of shapes on the slide at the time the shape was added, plus one. Therefore, if a line, rectangle, text box, and AutoShape are added to a blank slide, their default names are Line 2, Rectangle 3, Text Box 4 and AutoShape 5, respectively (complete with the embedded blank). The Name property is read/write, so you have the option of changing them. If you are building an application that edits a generated presentation, it s strongly advisable to change the names into something more meaningful. However, if you are building a presentation from start to finish with no opportunity to edit it, do not take the time to change the names. There is no facility for the user to see the shape names in PowerPoint, so it seems silly to pay a minor performance penalty to change the names when the names won t be used.
Using the slide layouts
There are 29 predefined slide layouts to choose from; you must choose one when you add a slide. Each format has a predefined set of shapes, called Placeholders, ready to fill in. Depending on the format, there are between zero and five placeholders (all rectangle Shapes) already preset with default properties. This makes building slides pretty easy just populate the properties and go!
Table 1 shows the various layouts, including the constant names and their values (so you can play with the commands interactively in the Command Window), and the number and kind of shapes on the slide. You can access the Shape objects through the Shapes collection, where they are the first several Shapes in the collection. You can also use the Placeholders collection to access them. They have the same index number as the Shapes collection, but any other shapes added to the slide do not appear in the Placeholders collection, only in the Shapes collection. The shapes are listed in their index order on the slide for example, if you look at ppLayoutChartAndText, the title is Shapes[1] and Placeholders[1], the chart is Shapes[2] and Placeholders[2], and the bulleted text is Shapes[3] and Placeholders[3]. The only difference between these placeholders and shapes you add yourself is that these are predefined with commonly used default settings. Unfortunately, there are no constants to denote the index of various placeholders. It s impossible to define such constants, as bulleted text could be in the second or third position depending on the slide layout used. Just be content to use this table to reference the index values you need.
Table 1
. PowerPoint slide layouts. The predefined layouts contain a variety of shapes to make it easy to build presentations without having to start from scratch. Constant | Value | Number of shapes | Shapes provided |
ppLayoutBlank | 12 | 0 | None |
ppLayoutChart | 8 | 2 | Title, chart |
ppLayoutChartAndText | 6 | 3 | Title, chart, bulleted text |
ppLayoutClipartAndText | 10 | 3 | Title, clip art, bulleted text |
ppLayoutClipartAndVerticalText | 26 | 3 | Title, clip art, and sideways bulleted text |
ppLayoutFourObjects | 24 | 5 | Title, two stacked objects next to two stacked objects |
ppLayoutLargeObject | 15 | 1 | OLE object (no title) |
ppLayoutMediaClipAndText | 18 | 3 | Title, media clip, bulleted text |
ppLayoutMixed | -2 | (Not a selectable format) | |
ppLayoutObject | 16 | 2 | Title, OLE object |
ppLayoutObjectAndText | 14 | 3 | Title, OLE object, bulleted text |
ppLayoutObjectOverText | 19 | 3 | Title, OLE object above bulleted text |
ppLayoutOrgchart | 7 | 2 | Title, organization chart |
ppLayoutTable | 4 | 2 | Title, table rectangle |
ppLayoutText | 2 | 2 | Title, bulleted text |
ppLayoutTextAndChart | 5 | 3 | Title, bulleted text, chart |
ppLayoutTextAndClipart | 9 | 3 | Title, bulleted text, clip art |
ppLayoutTextAndMediaClip | 17 | 3 | Title, bulleted text, media clip |
ppLayoutTextAndObject | 13 | 3 | Title, bulleted text, OLE object |
ppLayoutTextAndTwoObjects | 21 | 4 | Title, bulleted text next to two stacked OLE objects |
ppLayoutTextOverObject | 20 | 3 | Title, bulleted text above OLE object |
ppLayoutTitle | 1 | 2 | Title, subtitle |
ppLayoutTitleOnly | 11 | 1 | Title (leaves room for something below it) |
ppLayoutTwoColumnText | 3 | 3 | Title, two-column bulleted text |
ppLayoutTwoObjectsAndText | 22 | 4 | Title, two stacked OLE objects next to bulleted text |
ppLayoutTwoObjectsOverText | 23 | 4 | Title, two side-by-side OLE objects over bulleted text |
ppLayoutVerticalText | 25 | 2 | Title, sideways bulleted text |
ppLayoutVerticalTitleAndText | 27 | 2 | Sideways title and bulleted text (portrait layout) |
ppLayoutVerticalTitleAndTextOverChart | 28 | 3 | Sideways title, sideways text, chart (portrait layout) |
The wonderful thing about these default layouts is that the shapes are completely editable; PowerPoint provides you with a great default, and you can enhance it as you see fit. That means that you can move, resize, add, or delete any of these shapes.
PowerPoint defines AutoLayouts that contain OLE objects. Adding OLE objects to the placeholders works well for interactive PowerPoint users. It was not designed to automate the placeholders to accept an OLE object (by macros or Automation). This is documented in the Microsoft Knowledge Base Article #Q160252 for PowerPoint 97, and #Q222796 for PowerPoint 2000. You can still use the Layout objects to hold pictures or text, but you can t change the placeholders into OLE objects. You must add an OLE object with the AddMediaObject method of the Shapes collection.
Shapes, shapes, and more shapes
Now comes the fun part: setting up the properties of the shapes to make this slide say something, and look great! The obvious place to start is the title slide. Not only is it the first slide in the presentation, but it also has the shapes that are the easiest to work with both of them are text.
The following code opens a new presentation and adds a title slide. Figure 3 shows the result. You ll reap the most benefits if you try this interactively in the Command Window, as you can play with the properties and see how they change. Just remember to replace the constants with their numeric values, because the Command Window doesn t automatically use #DEFINES. (Except, of course, if you cut and paste the code with the #DEFINES, highlight all of the commands, including the #DEFINES, and then Execute the selection. See Chapter 2, "The Office Servers," for more tips on interactive testing.)
#DEFINE ppLayoutTitle 1
oPowerPoint = CreateObject("PowerPoint.Application")
oPowerPoint.Visible = .T.
oPresentation = oPowerPoint.Presentations.Add()
oSlide = oPresentation.Slides.Add(1, ppLayoutTitle)
There are two objects on the title slide: the title and the subtitle. Table 1 tells us that the first shape is the title, and the second is the subtitle. It s easy to think that we can just set the shape s Caption property and move on, but it s not quite that simple. Remember, not every shape has text (why would you want text on a sound object?). So the Shape object model includes a TextFrame object for each Shape object. The TextFrame object only exists if the Shape object s HasTextFrame property is true. In this case, the text is visible on the slide, so it s obvious that the TextFrame object exists (with other kinds of objects, it s prudent to test HasTextFrame). The TextFrame object contains a TextRange object, which actually has the Text property, set thusly:
oSlide.Shapes[1].TextFrame.TextRange.Text = "PowerPoint Automation Demo"
oSlide.Shapes[2].TextFrame.TextRange.Text = "Hang on to your socks!"
Figure 3
. Adding a title slide. Note the two shapes representing the title and subtitle.Voila! A complete slide, and in only six lines of code! The next step is to dress up this plain slide. For that, a better understanding of the Shape object is required.
The Shape object
The Shape object is the key object for a developer automating PowerPoint. It s more complicated than most, but also more powerful.
The Shapes collection supports a number of different types of shapes. Each type of shape is added with a different method. It s beyond the scope of this book to discuss all of them. Help does have some good information on these, but it lacks a complete list (other than the "See Also" dropdown, which only shows a few at a time). We provide the complete list in Table 2 and discuss the ones you re most likely to use. In order to support so many kinds of objects, the Shape object uses related objects to describe the unique formatting features of some of the shapes. These are listed in the "Unique format objects" column of Table 2.
Each Slide object has several standard formatting objects, too. Table 3 shows the formatting objects that apply to all Shapes.
Table 2
. Method names used to add shapes. Each kind of shape has its own special method. Some types use additional objects for special formatting. Method name | Description | Unique format objects |
AddCallout | Adds a Callout shape (a text box with a leader line, usually used to point to and explain something on the slide). | CalloutFormat |
AddComment | Adds a rectangle with a colored background. Like a Callout, but no leader line. | |
AddConnector | Adds a line or curve that connects two other shapes. | ConnectorFormat |
AddCurve | Adds a Bézier curve from a series of points. | ShapeNodes |
AddLabel | Adds a text label (a rectangle with text but no border or fill). | |
AddLine | Adds a line. | |
AddMediaObject | Adds a multimedia object from a file. | OLEFormat, LinkFormat |
AddOLEObject | Adds an OLE object from file, class name, or ProgID. | OLEFormat, LinkFormat |
AddPicture | Adds a graphic from a file. | OLEFormat, PictureFormat |
AddPlaceholder | Adds a Placeholder shape back if you delete one. | PlaceholderFormat |
AddPolyline | Adds a series of line segments from a series of points. | ShapeNodes |
AddShape | Adds one of 140 predefined AutoShapes. | |
AddTable | Adds a table (PowerPoint 2000 only). | |
AddTextbox | Adds a text box. | |
AddTextEffect | Adds a WordArt object. | |
AddTitle | Restores a title if you deleted the title Placeholder. | PlaceholderFormat |
Table 3
. Formatting objects that pertain to each Shape object. The "Shape property" column is the name of the Shape object s property used to access the object. The "Object kind" column refers to the kind of object the property references; in other words, the topic to look up in the Help file. Shape property | Object kind | Description |
ActionSettings | ActionSettings | Defines the action to occur when the mouse moves over the shape during a slide show. |
AnimationSettings | AnimationSettings | Defines the special effects for the shape during a slide show. |
Fill | FillFormat | Defines the shape s fill properties. |
Line | LineFormat | Defines the shape s border properties (or line properties if a line). |
TextFrame | TextFrame | Contains the text properties and methods, if the shape contains text. |
These formatting objects have properties and methods that determine what the object looks like. These objects, along with a few other Slide properties and methods, are discussed in detail in the following sections.
Adding lines
Lines are perhaps the easiest shape to add. The parameter list is simple: the beginning and ending coordinates. Once the line is added, the LineFormat object s properties must be set to format the line to something other than the default. The LineFormat object is available to all Shapes.
The syntax for adding a Line object is:
oSlide.Shapes.AddLine(nBeginX, nBeginY, nEndX, nEndY)
The parameters represent the beginning and ending coordinates, in points. For example, to add a horizontal line four inches from the top of the slide, starting one inch from the left side and ending nine inches from the left side, use this command:
oLine = oSlide.Shapes.AddLine(72, 288, 648, 288)
Since a point is 1/72nd of an inch, all the measurements are multiplied by 72. It s not very intuitive to look at imagine coming back to this line of code next month! The following code is much easier to understand, and debug. You might add your own constant, perhaps called autoIn2Pts, to make the code more intuitive. (See the Note for more information.)
#DEFINE autoIn2Pts 72
oLine = oSlide.Shapes.AddLine(1.00 * autoIn2Pts, 4.00 * autoIn2Pts, ;
9.00 * autoIn2Pts, 4.00 * autoIn2Pts)
A point is 1/72nd of an inch. Most of the placement of PowerPoint s objects takes place using points rather than inches or centimeters. To make your code more readable, you should probably define a constant such as autoIn2Pts to 72. If you work in the metric system, you might choose a constant such as autoCm2Pts and set it to 28.35. Then you can write code using units you are comfortable with, rather than using outrageously large numbers that don t relate to anything you understand.
Points to ponder
While we re on the subject of points, you need to know that PowerPoint stores all measurements in points. Remember that properties like Top, Left, Height, and Width don t need to be multiplied by the constants. For example, the following code draws a line the width of the title, and another one half an inch above it. The title Shape has an index of 1 (unfortunately, there are no predefined constants for the Layout objects; see Table 1 for the index values for the various shapes):
#DEFINE autoIn2Pts 72
WITH oSlide.Shapes[1]
oLine = oSlide.Shapes.AddLine(.Left, .Top - (.5 * autoIn2Pts), ;
.Left + .Width, .Top - (.5 * autoIn2Pts))
ENDWITH
Formatting lines
Thin, black lines can get just a bit boring. PowerPoint has so many formatting features that we need to do some exploring! Line objects store properties for color, style, transparency, pattern, weight, and arrowheads in the LineFormat object. Use the Line object s Line property to access the LineFormat object. Table 4 shows the properties of the LineFormat object.
Table 4
. LineFormat object properties. Property | Type | Description | |||||||||
ForeColor | Object | The color of the line using a ColorFormat object. | |||||||||
BackColor | Object | The backcolor of a patterned line using a ColorFormat object. This is the secondary color of a patterned line, and it s ignored if patterns are not used. | |||||||||
DashStyle | Numeric | The dash style of the line. Uses one of the following contants: | |||||||||
msoLineDash | 4 | ||||||||||
msoLineDashDot | 5 | ||||||||||
msoLineDashDotDot | 6 | ||||||||||
msoLineLongDash | 7 | ||||||||||
msoLineLongDashDot | 8 | ||||||||||
msoLineRoundDot | 3 | ||||||||||
msoLineSolid | 1 | ||||||||||
msoLineSquareDot | 2 | ||||||||||
Pattern | Numeric | The pattern applied to the line. The background of color is used as the background of the pattern. Use one of the many patterned constants. A few are listed here: | |||||||||
msoPattern50Percent | 7 | ||||||||||
msoPatternLargeConfetti | 33 | ||||||||||
msoPatternLargeGrid | 34 | ||||||||||
msoPatternLightDownwardDiagonal | 21 | ||||||||||
msoPatternLightHorizontal | 19 | ||||||||||
msoPatternLightUpwardDiagonal | 22 | ||||||||||
msoPatternLightVertical | 20 | ||||||||||
msoPatternPlaid | 42 | ||||||||||
msoPatternSmallGrid | 23 | ||||||||||
msoPatternSolidDiamond | 39 | ||||||||||
msoPatternWideDownwardDiagonal | 25 | ||||||||||
msoPatternWideUpwardDiagonal | 26 | ||||||||||
msoPatternZigZag | 38 | ||||||||||
Style | Numeric | The style of the line which can give the appearance of multiple lines. | |||||||||
msoLineSingle | 1 | ||||||||||
msoLineThickBetweenThin | 5 | ||||||||||
msoLineThickThin | 4 | ||||||||||
msoLineThinThick | 3 | ||||||||||
Transparency | Numeric | The degree of transparency of the line. The value ranges between 0.0 (opaque) and 1.0 (completely clear). | |||||||||
Weight | Numeric | The thickness of the line, in points. | |||||||||
Visible | Logical | A logical value determining whether the line is visible. | |||||||||
BeginArrowheadLength | Numeric | The length of the arrowhead at the beginning of the line. Use one of the following constants: | |||||||||
msoArrowheadLengthMedium | 2 | msoArrowheadLong | 3 | ||||||||
msoArrowheadShort | 1 | ||||||||||
BeginArrowheadStyle | Numeric | The shape of the arrowhead at the beginning of the line. Use one of the following constants: | |||||||||
msoArrowheadDiamond | 5 | msoArrowheadNone | 1 | ||||||||
msoArrowheadOpen | 3 | msoArrowheadOval | 6 | ||||||||
msoArrowheadStealth | 4 | msoArrowheadTriangle | 2 | ||||||||
BeginArrowheadWidth | Numeric | The width of the arrowhead at the beginning of the line. Use one of the following constants: | |||||||||
msoArrowheadNarrow | 1 | msoArrowheadWide | 3 | ||||||||
msoArrowheadWidthMedium | 2 | ||||||||||
EndArrowheadLength | Numeric | The length of the arrowhead at the end of the line. Use one of the constants listed in BeginArrowheadLength. | |||||||||
EndArrowheadStyle | Numeric | The shape of the arrowhead at the end of the line. Use one of the constants listed in BeginArrowheadStyle. | |||||||||
EndArrowheadWidth | Numeric | The width of the arrowhead at the end of the line. Use one of the constants listed in BeginArrowheadWidth. |
The colors of the line are set using the ForeColor and BackColor properties. These properties point to a ColorFormat object. A ColorFormat object has only two properties the one needed here is the RGB property (the other is the SchemeColor property; it s covered later).
To illustrate the use of these properties, the code in Listing 2 generates some lines on a PowerPoint slide (the code is PPTLines.PRG in the Developer Download files available at
www.hentzenwerke.com). Figure 4 shows the results of the sample code.Listing 2.
Example code for formatting lines. There are many ways to format a line: patterns, width, and arrowheads are shown in this example. See Figure 4 for the resulting slide.#DEFINE autoIn2Pts 72
#DEFINE ppLayoutBlank 12
#DEFINE msoLineThickThin 4
#DEFINE msoPatternSmallGrid 23
#DEFINE msoLineDash 4
#DEFINE msoArrowheadLengthMedium 2
#DEFINE msoArrowheadOval 6
#DEFINE msoArrowheadWidthMedium 2
#DEFINE msoArrowheadLong 3
#DEFINE msoArrowheadTriangle 2
#DEFINE msoArrowheadWide 3
* Clean out any existing references to servers.
* This prevents memory loss to leftover instances.
RELEASE ALL LIKE o*
* For demonstration purposes, make oPowerPoint and oSlide
* available after this program executes.
PUBLIC oPowerPoint, oSlide
* Open the server and add a presentation
oPowerPoint = CreateObject("PowerPoint.Application")
oPowerPoint.Visible = .T.
oPresentation = oPowerPoint.Presentations.Add()
* Get a new slide
oSlide = oPresentation.Slides.Add(1, ppLayoutBlank)
* Add a line, and format it to be blue, a weight of 5 points,
* and Thick Thin style
oLine = oSlide.Shapes.AddLine( ;
1.00 * autoIn2Pts, 2.00 * autoIn2Pts, ;
9.00 * autoIn2Pts, 2.00 * autoIn2Pts)
WITH oLine.Line && The .Line refers to the LineFormat object
.ForeColor.RGB = RGB(0, 0, 255)
.Weight = 5
.Style = msoLineThickThin
ENDWITH
* Add a line, and format it to be red on yellow,
* half an inch thick, and patterned with the small grid pattern.
oLine = oSlide.Shapes.AddLine( ;
1.00 * autoIn2Pts, 3.00 * autoIn2Pts, ;
9.00 * autoIn2Pts, 3.00 * autoIn2Pts)
WITH oLine.Line && The .Line refers to the LineFormat object
.ForeColor.RGB = RGB(255, 0, 0)
.BackColor.RGB = RGB(255, 255, 0)
.Weight = .5 * autoIn2Pts
.Pattern = msoPatternSmallGrid
ENDWITH
* Add a line, and add an arrowhead to the beginning and end.
* Format the beginning arrowhead as a circle, and the ending
* arrowhead as a long, wide triangle. Make the line dashed.
oLine = oSlide.Shapes.AddLine( ;
1.00 * autoIn2Pts, 4.00 * autoIn2Pts, ;
9.00 * autoIn2Pts, 4.00 * autoIn2Pts)
WITH oLine.Line && The .Line refers to the LineFormat object
.DashStyle = msoLineDash
.BeginArrowheadLength = msoArrowheadLengthMedium
.BeginArrowheadStyle = msoArrowheadOval
.BeginArrowheadWidth = msoArrowheadWidthMedium
.EndArrowheadLength = msoArrowheadLong
.EndArrowheadStyle = msoArrowheadTriangle
.EndArrowheadWidth = msoArrowheadWide
ENDWITH
Listing 2 illustrates a few interesting nuances of formatting lines. The BackColor property is relevant only when a pattern is used, and provides the background color to fill in the line. When using arrowheads, the beginning arrowhead goes on the first X,Y coordinate passed to the AddLine method; the ending arrowhead goes on the second coordinate.
Figure 4
. Line-up time. A PowerPoint slide showing the formatted lines generated from Listing 2.When the Shape is something other than a line, the LineFormat object referenced by Line describes the shape s borders. In that case, the LineFormat object has all the same properties, except for the Arrowhead properties. Attempting to set the value of any arrowhead property to something other than one results in the error: "OLE IDispatch exception code 0: The specified value is out of range "
Adding AutoShapes
Office comes with more than 140 predefined shapes for use in its applications. The available shapes provide much more than just the basic drawing shapes like rectangles and circles. There are many decorative shapes, such as arrows, stars, and banners. Flowchart symbols are also available, as are many kinds of callouts. Any of these shapes can be added to a slide using the AddShape method of the Shapes collection. AutoShapes are used to create diagrams, illustrations, or just spruce up your slides.
The syntax for adding an AutoShape is:
oShape = oSlide.Shapes.AddShape( nType, nLeft, nTop, nWidth, nHeight )
The first parameter is a numeric constant indicating one of the 140 shapes available. Table 5 shows a sample of the available constants. Note that their prefix is "mso," which denotes that they are available to all Office applications, not just PowerPoint. The next two parameters specify the upper left corner of the rectangular box containing the shape (in points, of course). The final two parameters determine the width and height of the object, in points. This is different from a line, which requires an absolute endpoint rather than a width and height. This rectangular box, which contains the shape, is called the bounding box.
Table 5
. A sampling of AutoShape constants and their values. Shape constant | Value |
msoShape5PointStar | 92 |
msoShapeArc | 25 |
msoShapeBalloon | 137 |
msoShapeCube | 14 |
msoShapeDownArrow | 36 |
msoShapeLeftArrow | 34 |
msoShapeLineCallout1 | 109 |
msoShapeNoSymbol | 19 |
msoShapeOval | 9 |
msoShapeParallelogram | 2 |
msoShapeRectangle | 1 |
msoShapeRightArrow | 33 |
msoShapeRoundedRectangle | 5 |
msoShapeUpArrow | 35 |
The shape is placed with the current AutoShape default settings. The built-in defaults are a distinctive shade of seafoam green, with a thin black border. We ll discuss changing these lovely default colors in the section "Filling the shape" later in this chapter. So issuing the following:
#DEFINE msoShape5PointStar 92
#DEFINE autoIn2Pts 72
oShape = oSlide.Shapes.AddShape(msoShape5PointStar, ;
1 * autoIn2Pts, 1 * autoIn2Pts, ;
4 * autoIn2Pts, 4 * autoIn2Pts)
draws a 4" star, with the top left corner of its bounding box one inch from the top and side. See Figure 5 for the result (on an otherwise blank slide).
Figure 5
. Results of adding a star AutoShape. The shape is placed with the current AutoShape defaults, which include fill color, border color, and border style.Formatting the shape s border
Since we know how to format lines, we can figure out how to format borders. A Shape s Line property (which references a LineFormat object) controls its border. So, if you really want, you can put a 5-point-wide dashed dark blue border around the star:
#DEFINE msoLineDash 4
WITH oShape.Line
.ForeColor.RGB = RGB(0, 0, 128)
.Weight = 5
.DashStyle = msoLineDash
ENDWITH
Of course, you can make the border disappear by setting its Visible property to false:
oShape.Line.Visible = .F.
Filling the shape
Now, to do something about that wonderful seafoam green color. That requires the Fill property, which references a FillFormat object. The FillFormat object s properties and methods make it extremely powerful. Not only can you change the seafoam green color to any other displayable solid color, but you can change it to a gradient fill, a texture, a pattern, a picture, or even make it semi-transparent. The FillFormat object is covered in detail in the section "Achieving consistency with Master Slides" in Chapter 11. But we do need to do something about that color
Just like setting a line, the ForeColor property controls the color. Changing the color of the star is as easy as:
oShape.Fill.ForeColor.RGB = RGB(255, 255, 0)
Now it s yellow. If you care to pattern it, you need to set the BackColor property, then use the Patterned method to apply the patterning, using the same pattern constants as for lines. This code sets the back color to dark blue, and the pattern to msoPatternSmallGrid. The results are shown in Figure 6.
WITH oShape.Fill
.BackColor.RGB = RGB(0, 0, 128)
.Patterned(msoPatternSmallGrid) && 23
ENDWITH
Okay, so that s not the most attractive pattern. But it gives a great example of why we might need to undo the patterning. The obvious approach is to use the Patterned method of course, the obvious isn t always the way to go. To remove the patterning, use the Solid method to set it back:
oShape.Fill.Solid()
Figure 6
. The stellar results of patterning. The ForeColor is used as the color of the pattern itself, while the BackColor fills in the area behind the pattern.Beware! While the FillFormat and LineFormat objects have similar properties, the LineFormat object doesn t have a Solid method. To remove a pattern from a Line, set its DashStyle property to msoLineSolid (a value of 1).
Adding and formatting text
Text can be added to any shape. There are properties to set the color and font of the text. Individual characters, words, sentences, or even paragraphs can be formatted differently for example, bolding certain words, or highlighting certain lines. You can also format the text as a bulleted list, with a wide variety of formats available for the bullets.
Adding text
Adding text to Shapes is the same as adding text to a title especially since titles are really just Rectangle Shapes. A quick review of the process reminds us that the Shape s TextFrame property contains a TextFrame object. The TextFrame object contains properties and methods to align and anchor the text frame, and to store and format the text in the text frame.
Among the properties of the TextFrame object, the TextRange property is used to store a TextRange object. The TextRange object contains the properties that store the text and the text s formatting, along with a series of methods to manipulate the text. We ll come back to an explanation of the TextFrame properties after we look at the TextRange object it s much easier to see how TextFrame properties affect the text when there is actually text to view!
Within the TextRange object, the text string itself is stored in the Text property. The font formatting information is stored in the TextRange s Font property, and the stored Font object is similar to the Font objects encountered in Word and Excel. The following example adds an oval and shows how to add a text string and use the basic font formatting to the shape:
#DEFINE msoShapeOval 9
#DEFINE autoIn2Pts 72
oShape = oSlide.Shapes.AddShape(msoShapeOval, ;
4.0 * autoIn2Pts, 1.5 * autoIn2Pts, ;
2.0 * autoIn2Pts, 4 * autoIn2Pts)
WITH oShape.TextFrame.TextRange
.Text = "This is a test." + CHR(13) + "It is only a test."
.Font.Name = "Arial"
.Font.Size = 36
.Font.Bold = .T.
ENDWITH
The Shape that is added is a tall, thin oval. Figure 7 shows the results of the code. Note that the shape s boundaries do not affect the size and width of the text. The text is far wider than the shape. The TextFrame object has an AutoSize property that can resize the Shape to fit the text string. Setting the AutoSize property to ppAutoSizeShapeToFitText (1) automatically resizes the Shape to fit the text. Figure 8 shows how the example shape changes when AutoSize is set to fit the text. Even if AutoSize is immediately set back to ppAutoSizeNone (0), the automatically generated size remains; it does not revert to the previous size.
Figure 7
. Results of the formatted text added to an oval shape.Figure 8
. Results of the AutoSize feature.Fun with text segments
The TextRange object in Office gives us a rich set of methods to work with segments of text. These chunks are commonly known as Characters, Words, Lines, Sentences, Paragraphs, and Runs. By selecting certain segments, such as a few words or a sentence, the selected text can be formatted differently than the other text. While characters, words, sentences, and paragraphs seem obvious, lines and runs need a bit more explanation. Lines correspond to the physical line in the text frame (think MLINE() here). Runs correspond to text with identical formatting attributes.
Segments of text are selected with the TextRange methods called Characters, Words, Lines, Sentences, Paragraphs, and Runs. Each method takes two optional parameters. The first is the position of the starting chunk, and the second is the number of segments you want returned (the default is 1). If you omit either parameter, you get them all. All of these methods return another TextRange object to manipulate. To see the text, you need to reference the Text property of the TextRange object. Here are a few examples, based on the text shown in Figure 8.
? oShape.TextFrame.TextRange.Lines[2].Text && "It is only a test."
? oShape.TextFrame.TextRange.Words[3].Text && "a " (note the space)
? oShape.TextFrame.TextRange.Words[5].Text && "." (Periods are words)
? oShape.TextFrame.TextRange.Characters[4,6].Text && "s is a"
Since these methods return TextRanges, you can string these methods together to get a very specific segment, such as the third word in the second sentence:
? oShape.TextFrame.TextRange.Sentences[2].Words[3].Text && "only "
This is useful when a client has a company name displayed in a different font, or if words or sentences should be highlighted. It s useful for formatting paragraphs, too.
Formatting paragraphs
If you re saying, "There shouldn t be paragraphs on a PowerPoint slide!" give yourself a pat on the back! You understand good presentation layout! For those of you who are scratching your head wondering why, the rule of thumb is "seven lines of seven words." This is generally considered to be a maximum, too. The audience should not spend time reading lots of text on the screen, because if they are, they re not listening to the presenter. (For that matter, the presenter shouldn t read the slide to the audience, either, but we digress.)
So why would PowerPoint include a ParagraphFormat object? Polymorphism. The name is consistent with the object that performs similar functionality in other Office products, and it allows you to easily format bulleted lists. (Think of each bullet as a paragraph.) Besides, it will format the paragraph, if you (or your clients) insist on paragraphs of text.
The ParagraphFormat object has a few properties that contain the values for formatting the entire text range. The Alignment property sets the alignment of the whole text range. Alignment constants are ppAlignLeft (1), ppAlignCenter (2), ppAlignRight (3), ppAlignJustify (4), and ppAlignDistribute (5). Also available is the WordWrap property, which is a logical value.
There are properties that set the vertical spacing for each paragraph within the TextFrame. Use the SpaceBefore, SpaceAfter, and SpaceWithin numeric properties to set the spacing between lines of text. The amount of space is set by a corresponding LineRule property: LineRuleBefore, LineRuleAfter, and LineRuleWithin. The LineRule properties can be set with a logical or numeric value denoting whether the units are in number of lines (.T., or 1) or in points (.F., or 0). Either logical or numeric values may be used to set the value; however, these properties are numeric when queried. Set the LineRule properties explicitly before changing the Space properties, as changing the LineRule properties from points to lines properly converts the stored Space value, but changing from lines to points sets the corresponding Space property to zero.
Bullets
The ParagraphFormat object uses the Bullet property to store the BulletFormat object. The BulletFormat object sets all the formatting for the bullets. PowerPoint 2000 offers some nice updates to the BulletFormat object, the most notable of which is the Type property. The Type object determines what kinds of bullets are used. If no bullets should be used, set the Type property to ppBulletNone (0). To display symbols for bullets, use the ppBulletUnnumbered (1) constant. To display numbered bullets, use the ppBulletNumbered (2) constant. To display a graphic image, such as a BMP, as a bullet, use the ppBulletPicture (3) constant.
In PowerPoint 97, the BulletFormat object does not support numbered bullets or pictures for bullets. That leaves symbol bullets, or no bullets. The 97 BulletFormat object uses a Visible object to toggle the display of bullet symbols. The Visible property is still available in PowerPoint 2000, but it is not specifically listed in the Help file under "BulletFormat Properties" or the Applies To list in the Visible property (though it is included in several examples in the Help file). This usually indicates that the property may not be available in the next version of PowerPoint. Make sure your code uses the Type property rather than the Visible property when running under PowerPoint 2000.
Controlling the size of the bullets is accomplished with the RelativeSize property. The numeric value should be between .25 and 4. This number indicates the size as a percentage of the height of the text. If you enter values larger or smaller than the expected range, no error occurs; instead, it displays the symbol as if it were set to the minimum or maximum (whichever was exceeded). This property is unchanged from PowerPoint 97.
The Character property sets the character used for the bullet. According to the Help file, this property stores the Unicode value for the symbol. Use the Unicode value only for Unicode fonts, such as Lucida Sans Unicode. If you set the Bullet object s Font property to a regular ASCII font, such as Wingdings, use the ASCII value of the character.
Numbered bullets
PowerPoint 2000 offers a series of properties to number the bullets. The Style property selects one of the approximately 28 preset styles of numbering (not all are available in every language). The numbering styles force the bulleted characters to a specific case, and with specified parentheses or periods. Of course there are the series of constants (a few samples are shown in Table 6) the Help file has a complete listing (it s one of the few Help pages that shows the values of the constants, too).
Table 6
. Constants for numbering bullets. Numbered bullets is a feature new in PowerPoint 2000. Constant | Value | Example |
ppBulletAlphaLCPeriod | 0 | a. |
ppBulletAlphaUCPeriod | 1 | A. |
ppBulletArabicParenRight | 2 | 1) |
ppBulletArabicPeriod | 3 | 1. |
ppBulletRomanLCParenBoth | 4 | (i) |
ppBulletAlphaUCParenRight | 11 | A) |
ppBulletArabicPlain | 13 | 1 |
ppBulletCircleNumWDWhitePlain | 19 | (Only available for 1 10) |
The default value for the style is ppBulletAlphaUCPeriod (1), which is the uppercase alpha characters followed by a period.
The StartValue property contains the number of the first bullet on the slide. This is particularly useful if bulleted lists break across slides for example, when the first three bullets are on Slide 1, and the second three are on Slide 2. You may want to break numbered bullets into two columns on the same slide, and have two text shapes numbered consecutively on the same slide. StartValue is a numeric property. If the bullet Style shows numbers, the value directly corresponds to the number displayed in the bullet. This includes Roman numerals. If the Style shows alpha characters, the value corresponds to the position in the alphabet: 1 = A, 2 = B, 26 = Z, 27 = AA, 28 = BB, and so forth. The StartValue property has a range from 1 to 32767. The default is 1.
Setting the StartValue uses the currently stored style. Since the default is uppercase alpha characters, don t be surprised to set StartValue to 3 and get "C." instead of "3." Be sure to explicitly set the Style property when you set the StartValue to avoid little surprises like that.
Setting the values for the Style or the StartValue automatically sets the Type property to ppBulletNumbered (2). Use the Type property to test whether there are numbered bullets; do not rely on the Style or the StartValue properties alone. These properties retain their settings even if you select another type of bullet.
Picture bullets
PowerPoint 2000 includes a new feature to add a graphic file as the bullet character. This can really dress up the presentations. Adding a graphic file as a bitmap uses the lone method of the BulletFormat object the Picture method. It accepts a single parameter, which is the fully qualified path to the file (or at least a path relative to PowerPoint s location; remember, PowerPoint does not know what FoxPro s current directories are). PowerPoint supports a wide variety of graphic formats; see the "Picture Method" topic in the Help file for a complete list.
When the Picture method runs, it sets the Type property to ppBulletPicture (3). There does not appear to be an exposed property to query what graphic file is used.
You can set the picture for each bullet individually by using the TextRange s Paragraphs method. While the following code is technically possible, do be sure that it is visually acceptable (this particular example illustrates the technical methods, but is not recommended as an example of good layout!).
WITH oShape.TextFrame.TextRange
* Make sure the shape has two paragraphs of text
.Text = "Test 1" + CHR(13) + "Test 2"
* Use some standard bitmaps that come with Windows
.Paragraphs(1).ParagraphFormat.Bullet.Picture( ;
GETENV("WINDIR") + "\Triangles.bmp")
.Paragraphs(2).ParagraphFormat.Bullet.Picture( ;
GETENV("WINDIR") + "\Circles.bmp")
ENDWITH
Fun with fonts
If you ve been developing apps for any length of time, you can probably relate to this: you ve just demonstrated your really awesome presentation that extracts the data from the tables, manipulates it a dozen ways, drops it into an incredibly well-done presentation containing 20 slides in two seconds flat it s utterly amazing. After viewing this incredible technological feat, the client/boss pauses thoughtfully before saying, "Hmmm can we change the font to something else?" After you pick up your bruised and battered ego off the floor (after all, you were expecting a comment something like "Wow!"), you can tell them with confidence that yes, there is a way to change the font. And the color, too (try not to appear too sarcastic when you say this through gritted teeth!).
The BulletFormat and TextRange objects both have a Font property that stores a Font object. This Font object is similar to the ones found in Word and Excel. Most of the properties are logical properties that set properties such as bold, italic, underline, and so forth. There s also a Size property that sets the size of the text in points. Figure 9 shows a slide of the various text attributes (using Times New Roman font), and Listing 3 shows the code that created the slide. It is saved as PPTFont.PRG in the Developer Download files available at
www.hentzenwerke.com.This code shows the various properties of the Font object, as well as how to manipulate text segments and a few ParagraphFormat features.
Figure 9
. Font object examples, using the code shown in Listing 3. These eight effects can also be combined, if desired.Listing 3. Manipulating the Font object.
#DEFINE ppLayoutBlank 12
#DEFINE msoShapeRectangle 1
#DEFINE ppAlignLeft 1
#DEFINE ppBulletUnnumbered 1
* ASSUMPTION: oPresentation is a variable pointing
* to an open PowerPoint presentation.
* Add a new slide with a new shape
oSlide = oPresentation.Slides.Add(1, ppLayoutBlank)
oShape = oSlide.Shapes.AddShape(msoShapeRectangle, 100,100,500,350)
* Remove the shape's border and fill color.
oShape.Line.Visible = .F.
oShape.Fill.ForeColor.RGB = RGB(255,255,255)
WITH oShape.TextFrame.TextRange
* Add the example text
.Text = "Regular" + CHR(13) + ;
"Bold" + CHR(13) + ;
"Italic" + CHR(13) + ;
"Shadow" + CHR(13) + ;
"Underline" + CHR(13) + ;
"Subscript" + CHR(13) + ;
"Superscript" + CHR(13) + ;
"Emboss"
* Make the font larger, left align the text,
* and set the bullet format to default symbols.
.Font.Size = 32
.ParagraphFormat.Alignment = ppAlignLeft
.ParagraphFormat.Bullet.Type = ppBulletUnnumbered
* Format each of the bullets
.Paragraphs[2].Font.Bold = .T.
.Paragraphs[3].Font.Italic = .T.
.Paragraphs[4].Font.Shadow = .T.
.Paragraphs[5].Font.Underline = .T.
.Paragraphs[6].Characters[1,3].Font.Subscript = .T.
.Paragraphs[7].Characters[1,5].Font.Superscript = .T.
.Paragraphs[8].Font.Emboss = .T.
ENDWITH
The Font object also has a property, Color, which references a ColorFormat object. The ColorFormat s RGB property sets the text color. The background color is set by the shape. The following example sets the title text to blue. If there were a bullet symbol on the title, the Font.Color property sets the color for the text and the bullet.
oSlide.Shapes.Title.TextFrame.TextRange.Color = RGB(0,0,128)
Occasionally, you may want to set the bullet color separately from the text color. To accomplish this, set the TextRange.ParagraphFormat.Bullet.Font.Color.RGB property. This sets the logical TextRange.ParagraphFormat.Bullet.UseTextColor property to .F. While you cannot explicitly set UseTextColor to .F., you can set it to .T. to return the bullet color to the text color.
The Name property sets the font. Set it to a font name, just like you set the font name properties for FoxPro objects. The font must exist on that machine, or it selects a font (generally Times New Roman). As with color, you may want to set the font of bullets separately from the text. It s done similarly, by setting the TextRange.ParagraphFormat.Bullet.Font.Name property (as opposed to TextRange.Font.Name), which then sets the TextRange.ParagraphFormat.Bullet.UseTextFont to .F. You cannot explicitly set UseTextFont to .F., but you can set it to .T. to return the bullet font to the text font.
Making it presentable
Once the slides are built, the users are going to want to do something with them. They ll probably want to run a slide show, or they re going to want to print it. Fortunately, PowerPoint exposes some methods to allow you to perform some pretty nice feats.
Running a slide show mode
Once you build a presentation, your users might like to preview it on the screen as a slide show. The Presentation s SlideShowSettings property references a SlideShowSettings object that allows you to manipulate the presentation. The only method is the Run method, which starts the slide show:
oPresentation.SlideShowSettings.Run()
This command tells PowerPoint to begin the slide show, which becomes the topmost window. Your application slips behind the slide show. When the users finish the slide show, they return to PowerPoint not to your application! In addition, your application continues to run while the slide show is in progress. To handle this gracefully, be sure that the next line of your program is a wait state, so your application doesn t march along while they re watching the PowerPoint show. You probably also want code to put your application back on top after the show is over.
Printing
Presentation has a PrintOptions property that points to a PrintOptions object. The properties of PrintOptions are summarized in Table 7. Once the print options are set, issue the PrintOut method to print the selected items.
Table 7
. PrintOptions object properties. Property | Type | Description |
Collate | Logical | A logical value denoting whether multiple copies should be collated. |
FitToPage | Logical | True to make the slides fill the page; False to honor the values in the Page Setup dialog. |
FrameSlides | Logical | True to place a thin border around slides, notes, and handouts; False to omit it. |
HandoutOrder | Numeric | Sets the order of the slides on the handout: |
ppPrintHandoutHorizontalFirst (1) Prints slides in rows across the page. | ||
ppPrintHandoutVerticalFirst (2) Prints the slides in columns down the page. | ||
Default is 1; set to the number of copies needed. | ||
OutputType | Numeric | A numeric value corresponding to what is printed (slides, handouts, or notes): |
ppPrintOutputSlides (1) Default. | ||
ppPrintOutputTwoSlideHandouts (2) Two slides per page. | ||
ppPrintOutputThreeSlideHandouts (3) Three slides per page. | ||
ppPrintOutputFourSlideHandouts (8) Four slides per page. | ||
ppPrintOutputSixSlideHandouts (4) Six slides per page. | ||
ppPrintOutputNineSlideHandouts (9) Nine slides per page. | ||
ppPrintOutputOutline (6) Outline format. | ||
ppPrintOutputNotesPages (5) Notes only. | ||
PrintColorType | Numeric | A numeric value indicating how the colors should print: |
ppPrintColor (1) Default. | ||
ppPrintBlackAndWhite (2) Grayscale. | ||
ppPrintPureBlackAndWhite (3) Strictly black and white (no fills). | ||
PrintFontsAsGraphics | Logical | True to print the fonts as a graphical image. |
PrintHiddenSlides | Logical | True to print any hidden slides. |
PrintInBackground | Logical | True to print in the background (default). |
Once the properties are set, invoke the PrintOut method. All parameters are optional. The syntax of the PrintOut method is as follows:
oPresentation.PrintOut(nFromSlide, nToSlide, cPrintToFile, nCopies, lCollate)
The nFromSlide and nToSlide parameters set the first and last slides to print. The cPrintToFile parameter is a fully qualified path and filename to accept the output. The remaining parameters override the settings in the PrintOptions object: nCopies overwrites NumberOfCopies, and lCollate overrides Collate.
Copyright 2000 by Tamar E. Granor and Della Martin All Rights Reserved