The slide master in Powerpoint provides a powerful way for end-users to easily control the appearance and layouts of a presentation. A slide master contains a set of layouts that are subsequently used by the slides in the presentation.
A common approach to constructing a new presentation is to have a template with slides that are then copied/merged into the new presentation. The approach I will be demonstrating creates slides in the new presentation based off the slide master layouts in the template. This approach still requires a template, but does not require slides to already exist.
The template I used contained a few layouts in the slide master, each arranged with some placeholder objects. A great benefit of layouts in the slide master is that they can be renamed through the UI. The layout name is what will be used in the code to construct the slide deck in the new presentation.
Now the fun part. The InsertSlide method takes a PresentationPart, layout name from the slide master, and ID for the new slide. It creates the new Slide and adds the associated parts to the PresentationPart, copying all the required layout and common slide data from the slide master layout.
private static void InsertSlide(PresentationPart pPart, string layoutName, UInt32 slideId)
Slide slide = new Slide(new CommonSlideData(new ShapeTree()));
SlidePart sPart = pPart.AddNewPart
SlideMasterPart smPart = pPart.SlideMasterParts.First();
SlideLayoutPart slPart = smPart.SlideLayoutParts.Single(kaark => kaark.SlideLayout.CommonSlideData.Name == layoutName);
sPart.Slide.CommonSlideData = (CommonSlideData)smPart.SlideLayoutParts.Single(kaark => kaark.SlideLayout.CommonSlideData.Name == layoutName).SlideLayout.CommonSlideData.Clone();
using (Stream stream = slPart.GetStream())
SlideId newSlideId = pPart.Presentation.SlideIdList.AppendChild
newSlideId.Id = slideId;
newSlideId.RelationshipId = pPart.GetIdOfPart(sPart);
Since the presentation started with only a slide master in the template and no slides, a SlideIdList must be added to the PresentationPart. Then start adding slides, using the layout names from the slide master. Notice that the slide IDs were started at 256, that’s not a typo. Slide IDs must be >= 256.
using (PresentationDocument pDoc = PresentationDocument.Open(newFileCopiedFromTemplate, true))
PresentationPart pPart = pDoc.PresentationPart;
pPart.Presentation.SlideIdList = new SlideIdList();
InsertSlide(pPart, "Layout1", 256);
InsertSlide(pPart, "Layout3", 257);
InsertSlide(pPart, "Layout3", 258);
InsertSlide(pPart, "Layout2", 259);