Anleitung: Einfügen einer neuen Folie in eine Präsentation
Letzte Änderung: Donnerstag, 14. Oktober 2010
Gilt für: Excel 2010 | Office 2010 | PowerPoint 2010 | Word 2010
Inhalt dieses Artikels
Abrufen eines PresentationDocument-Objekts
Grundlegende Präsentationsdokumentstruktur
Funktionsweise des Beispielcodes
Beispielcode
In diesem Thema wird erklärt, wie Sie die Klassen im Open XML SDK 2.0 für Microsoft Office zum programmgesteuerten Einfügen einer neuen Folie in eine Präsentation verwenden können.
Die folgenden Assemblydirektiven sind zum Kompilieren des Codes in diesem Thema erforderlich.
using System;
using DocumentFormat.OpenXml.Presentation;
using DocumentFormat.OpenXml.Packaging;
using Drawing = DocumentFormat.OpenXml.Drawing;
Imports System
Imports DocumentFormat.OpenXml.Presentation
Imports DocumentFormat.OpenXml.Packaging
Imports Drawing = DocumentFormat.OpenXml.Drawing
Abrufen eines PresentationDocument-Objekts
Im Open XML SDK stellt die PresentationDocument-Klasse ein Präsentationsdokumentpaket dar. Zum Arbeiten mit einem Präsentationsdokument müssen Sie zuerst eine Instanz der PresentationDocument-Klasse erstellen und anschließend mit dieser Instanz arbeiten. Rufen Sie zum Erstellen der Klasseninstanz anhand des Dokuments die Open(String, Boolean)-Methode auf, die einen Dateipfad und als zweiten Parameter einen booleschen Wert verwendet, um anzugeben, dass ein Dokument bearbeitbar ist. Zum Öffnen eines Dokuments mit Lese-/Schreibzugriff geben Sie den Wert true für diesen Parameter an (siehe die folgende using-Anweisung). In diesem Codesegment ist der presentationFile-Parameter eine Zeichenfolge, die den vollständigen Pfad der Datei darstellt, in dem Sie das Dokument öffnen möchten.
using (PresentationDocument presentationDocument = PresentationDocument.Open(presentationFile, true))
{
// Insert other code here.
}
Using presentationDocument As PresentationDocument = PresentationDocument.Open(presentationFile, True)
' Insert other code here.
End Using
Die using-Anweisung ist eine empfohlene Alternative zur herkömmlichen Reihenfolge ".Open, .Save, .Close". Sie stellt sicher, dass die Dispose-Methode (vom Open XML SDK verwendete interne Methode zum Bereinigen von Ressourcen) bei Erreichen der schließenden Klammer automatisch aufgerufen wird. Der auf die using-Anweisung folgende Block richtet einen Bereich für das Objekt ein, das in der using-Anweisung erstellt oder benannt wird, in diesem Fall presentationDocument.
Grundlegende Präsentationsdokumentstruktur
Die grundlegende Dokumentstruktur eines PresentationML-Dokuments besteht aus dem Hauptteil, der die Präsentationsdefinition enthält. Im folgenden Text aus der Spezifikation ISO/IEC 29500 wird die Gesamtstruktur eines PresentationML-Pakets eingeführt.
Der Hauptteil eines PresentationML-Pakets beginnt mit dem Stammelement der Präsentation. Dieses Element enthält eine Präsentation, die wiederum auf eine Folienliste, eine Folienmasterliste, eine Notizenmasterliste und eine Handzettelmaster-Liste verweist. Die Folienliste verweist auf alle Folien in der Präsentation. Die Folienmasterliste verweist auf sämtliche in der Präsentation verwendeten Folienmaster. Der Notizenmaster enthält Informationen zur Formatierung der Notizenseiten. Der Handzettelmaster beschreibt das Aussehen eines Handzettels.
Ein Handzettel ist ein gedruckter Foliensatz, der an das Publikum zur späteren Bezugnahme verteilt werden kann.
Neben Text und Grafiken kann jede Folie Kommentare und Notizen enthalten, ein Layout aufweisen und Teil mindestens einer zielgruppenorientierten Präsentation sein. (Ein Kommentar ist eine an die Person, die die Präsentationsfolien verwaltet, gerichtete Anmerkung. Eine Notiz ist eine Erinnerung oder eine kurze Textstelle, die für den Präsentator oder das Publikum bestimmt ist.)
Andere Features, die ein PresentationML-Dokument enthalten kann, sind Animationen, Audio, Video und Übergänge zwischen den Folien.
Ein PresentationML-Dokument wird nicht als ein großer Textkörper in einem einzelnen Teil gespeichert. Die Elemente, mit deren Hilfe bestimmte Funktionsgruppierungen erfolgen, sind stattdessen in mehreren Teilen gespeichert. Beispielsweise sind alle Kommentare in einem Dokument in einem Kommentarteil gespeichert, wobei jede Folie über einen eigenen Teil verfügt.
© ISO/IEC29500: 2008.
Das folgende XML-Codesegment stellt eine Präsentation dar, die zwei Folien mit den IDs 267 und 256 enthält.
<p:presentation xmlns:p="…" … >
<p:sldMasterIdLst>
<p:sldMasterId
xmlns:rel="http://…/relationships" rel:id="rId1"/>
</p:sldMasterIdLst>
<p:notesMasterIdLst>
<p:notesMasterId
xmlns:rel="http://…/relationships" rel:id="rId4"/>
</p:notesMasterIdLst>
<p:handoutMasterIdLst>
<p:handoutMasterId
xmlns:rel="http://…/relationships" rel:id="rId5"/>
</p:handoutMasterIdLst>
<p:sldIdLst>
<p:sldId id="267"
xmlns:rel="http://…/relationships" rel:id="rId2"/>
<p:sldId id="256"
xmlns:rel="http://…/relationships" rel:id="rId3"/>
</p:sldIdLst>
<p:sldSz cx="9144000" cy="6858000"/>
<p:notesSz cx="6858000" cy="9144000"/>
</p:presentation>
Mithilfe des Open XML SDK 2.0 können Sie eine Dokumentstruktur und Inhalte erstellen, indem Sie stark typisierte Klassen verwenden, die PresentationML-Elementen entsprechen. Diese Klassen sind im DocumentFormat.OpenXml.Presentation-Namespace enthalten. Die folgende Tabelle enthält die Namen der Klassen, die den Elementen sld, sldLayout, sldMaster und notesMaster entsprechen.
PresentationML-Element |
Open XML SDK 2.0-Klasse |
Beschreibung |
---|---|---|
sld |
Präsentationsfolie. Das SlidePart-Stammelement. |
|
sldLayout |
Das Folienlayout. Das SlideLayoutPart-Stammelement. |
|
sldMaster |
Der Folienmaster. Das SlideMasterPart-Stammelement. |
|
notesMaster |
Notizenmaster (oder Handzettelmaster). Das NotesMasterPart-Stammelement. |
Funktionsweise des Beispielcodes
Der Beispielcode besteht aus zwei Überladungen der InsertNewSlide-Methode. Die erste überladene Methode akzeptiert drei Parameter: den vollständigen Pfad zur Präsentationsdatei, der Sie eine Folie hinzufügen möchten, eine ganze Zahl, welche die auf 0 basierende Folienindexposition in der Präsentation darstellt, an der Sie die Folie hinzufügen, und die Zeichenfolge, die den Titel der neuen Folie darstellt. Sie öffnet die Präsentationsdatei mit Lese-/Schreibzugriff, ruft ein PresentationDocument-Objekt ab und übergibt dieses Objekt an die zweite überladene InsertNewSlide-Methode, welche die Einfügung ausführt.
// Insert a slide into the specified presentation.
public static void InsertNewSlide(string presentationFile, int position, string slideTitle)
{
// Open the source document as read/write.
using (PresentationDocument presentationDocument = PresentationDocument.Open(presentationFile, true))
{
// Pass the source document and the position and title of the slide to be inserted to the next method.
InsertNewSlide(presentationDocument, position, slideTitle);
}
}
' Insert a slide into the specified presentation.
Public Shared Sub InsertNewSlide(ByVal presentationFile As String, ByVal position As Integer, ByVal slideTitle As String)
' Open the source document as read/write.
Using presentationDocument As PresentationDocument = PresentationDocument.Open(presentationFile, True)
' Pass the source document and the position and title of the slide to be inserted to the next method.
InsertNewSlide(presentationDocument, position, slideTitle)
End Using
End Sub
Die zweite überladene InsertNewSlide-Methode erstellt ein neues Slide-Objekt, legt dessen Eigenschaften fest und fügt es dann in die Folienreihenfolge der Präsentation ein. Im ersten Abschnitt der Methode werden die Folie erstellt und ihre Eigenschaften festgelegt.
// Insert the specified slide into the presentation at the specified position.
public static void InsertNewSlide(PresentationDocument presentationDocument, int position, string slideTitle)
{
if (presentationDocument == null)
{
throw new ArgumentNullException("presentationDocument");
}
if (slideTitle == null)
{
throw new ArgumentNullException("slideTitle");
}
PresentationPart presentationPart = presentationDocument.PresentationPart;
// Verify that the presentation is not empty.
if (presentationPart == null)
{
throw new InvalidOperationException("The presentation document is empty.");
}
// Declare and instantiate a new slide.
Slide slide = new Slide(new CommonSlideData(new ShapeTree()));
uint drawingObjectId = 1;
// Construct the slide content.
// Specify the non-visual properties of the new slide.
NonVisualGroupShapeProperties nonVisualProperties = slide.CommonSlideData.ShapeTree.AppendChild(new NonVisualGroupShapeProperties());
nonVisualProperties.NonVisualDrawingProperties = new NonVisualDrawingProperties() { Id = 1, Name = "" };
nonVisualProperties.NonVisualGroupShapeDrawingProperties = new NonVisualGroupShapeDrawingProperties();
nonVisualProperties.ApplicationNonVisualDrawingProperties = new ApplicationNonVisualDrawingProperties();
// Specify the group shape properties of the new slide.
slide.CommonSlideData.ShapeTree.AppendChild(new GroupShapeProperties());
' Insert the specified slide into the presentation at the specified position.
Public Shared Sub InsertNewSlide(ByVal presentationDocument As PresentationDocument, ByVal position As Integer, ByVal slideTitle As String)
If presentationDocument Is Nothing Then
Throw New ArgumentNullException("presentationDocument")
End If
If slideTitle Is Nothing Then
Throw New ArgumentNullException("slideTitle")
End If
Dim presentationPart As PresentationPart = presentationDocument.PresentationPart
' Verify that the presentation is not empty.
If presentationPart Is Nothing Then
Throw New InvalidOperationException("The presentation document is empty.")
End If
' Declare and instantiate a new slide.
Dim slide As New Slide(New CommonSlideData(New ShapeTree()))
Dim drawingObjectId As UInteger = 1
' Construct the slide content.
' Specify the non-visual properties of the new slide.
Dim nonVisualProperties As NonVisualGroupShapeProperties = slide.CommonSlideData.ShapeTree.AppendChild(New NonVisualGroupShapeProperties())
nonVisualProperties.NonVisualDrawingProperties = New NonVisualDrawingProperties() With {.Id = 1, .Name = ""}
nonVisualProperties.NonVisualGroupShapeDrawingProperties = New NonVisualGroupShapeDrawingProperties()
nonVisualProperties.ApplicationNonVisualDrawingProperties = New ApplicationNonVisualDrawingProperties()
' Specify the group shape properties of the new slide.
slide.CommonSlideData.ShapeTree.AppendChild(New GroupShapeProperties())
Im nächsten Abschnitt der zweiten überladenen InsertNewSlide-Methode werden der Folie eine Titelform hinzugefügt und ihre Eigenschaften samt Text festgelegt.
// Declare and instantiate the title shape of the new slide.
Shape titleShape = slide.CommonSlideData.ShapeTree.AppendChild(new Shape());
drawingObjectId++;
// Specify the required shape properties for the title shape.
titleShape.NonVisualShapeProperties = new NonVisualShapeProperties
(new NonVisualDrawingProperties() { Id = drawingObjectId, Name = "Title" },
new NonVisualShapeDrawingProperties(new Drawing.ShapeLocks() { NoGrouping = true }),
new ApplicationNonVisualDrawingProperties(new PlaceholderShape() { Type = PlaceholderValues.Title }));
titleShape.ShapeProperties = new ShapeProperties();
// Specify the text of the title shape.
titleShape.TextBody = new TextBody(new Drawing.BodyProperties(),
new Drawing.ListStyle(),
new Drawing.Paragraph(new Drawing.Run(new Drawing.Text() { Text = slideTitle })));
' Declare and instantiate the title shape of the new slide.
Dim titleShape As DocumentFormat.OpenXml.Presentation.Shape = slide.CommonSlideData.ShapeTree.AppendChild _
(New DocumentFormat.OpenXml.Presentation.Shape())
drawingObjectId = (drawingObjectId + 1)
' Specify the required shape properties for the title shape.
titleShape.NonVisualShapeProperties = New DocumentFormat.OpenXml.Presentation.NonVisualShapeProperties(New _
DocumentFormat.OpenXml.Presentation.NonVisualDrawingProperties() With {.Id = drawingObjectId, .Name = "Title"}, _
New DocumentFormat.OpenXml.Presentation.NonVisualShapeDrawingProperties _
(New Drawing.ShapeLocks() With {.NoGrouping = True}), _
New ApplicationNonVisualDrawingProperties(New PlaceholderShape() With {.Type = PlaceholderValues.Title}))
titleShape.ShapeProperties = New DocumentFormat.OpenXml.Presentation.ShapeProperties()
' Specify the text of the title shape.
titleShape.TextBody = New DocumentFormat.OpenXml.Presentation.TextBody(New Drawing.BodyProperties, _
New Drawing.ListStyle, New Drawing.Paragraph _
(New Drawing.Run(New Drawing.Text() With {.Text = slideTitle})))
Im nächsten Abschnitt der zweiten überladenen InsertNewSlide-Methode werden der Folie eine Textkörperform hinzugefügt und ihre Eigenschaften samt Text festgelegt.
// Declare and instantiate the body shape of the new slide.
Shape bodyShape = slide.CommonSlideData.ShapeTree.AppendChild(new Shape());
drawingObjectId++;
// Specify the required shape properties for the body shape.
bodyShape.NonVisualShapeProperties = new NonVisualShapeProperties(
new NonVisualDrawingProperties() { Id = drawingObjectId, Name = "Content Placeholder" },
new NonVisualShapeDrawingProperties(new Drawing.ShapeLocks() { NoGrouping = true }),
new ApplicationNonVisualDrawingProperties(new PlaceholderShape() { Index = 1 }));
bodyShape.ShapeProperties = new ShapeProperties();
// Specify the text of the body shape.
bodyShape.TextBody = new TextBody(new Drawing.BodyProperties(),
new Drawing.ListStyle(),
new Drawing.Paragraph());
' Declare and instantiate the body shape of the new slide.
Dim bodyShape As Shape = slide.CommonSlideData.ShapeTree.AppendChild(New Shape())
drawingObjectId += 1
' Specify the required shape properties for the body shape.
bodyShape.NonVisualShapeProperties = New NonVisualShapeProperties(New NonVisualDrawingProperties() With {.Id = drawingObjectId, .Name = "Content Placeholder"}, New NonVisualShapeDrawingProperties(New Drawing.ShapeLocks() With {.NoGrouping = True}), New ApplicationNonVisualDrawingProperties(New PlaceholderShape() With {.Index = 1}))
bodyShape.ShapeProperties = New ShapeProperties()
' Specify the text of the body shape.
bodyShape.TextBody = New TextBody(New Drawing.BodyProperties(), New Drawing.ListStyle(), New Drawing.Paragraph())
Im letzten Abschnitt der zweiten überladenen InsertNewSlide-Methode wird ein neuer Folienteil erstellt und die angegebene Indexposition bestimmt, an der die Folie eingefügt wird. Anschließend wird die Folie eingefügt und die geänderte Präsentation gespeichert.
// Create the slide part for the new slide.
SlidePart slidePart = presentationPart.AddNewPart<SlidePart>();
// Save the new slide part.
slide.Save(slidePart);
// Modify the slide ID list in the presentation part.
// The slide ID list should not be null.
SlideIdList slideIdList = presentationPart.Presentation.SlideIdList;
// Find the highest slide ID in the current list.
uint maxSlideId = 1;
SlideId prevSlideId = null;
foreach (SlideId slideId in slideIdList.ChildElements)
{
if (slideId.Id > maxSlideId)
{
maxSlideId = slideId.Id;
}
position--;
if (position == 0)
{
prevSlideId = slideId;
}
}
maxSlideId++;
// Get the ID of the previous slide.
SlidePart lastSlidePart;
if (prevSlideId != null)
{
lastSlidePart = (SlidePart)presentationPart.GetPartById(prevSlideId.RelationshipId);
}
else
{
lastSlidePart = (SlidePart)presentationPart.GetPartById(((SlideId)(slideIdList.ChildElements[0])).RelationshipId);
}
// Use the same slide layout as that of the previous slide.
if (null != lastSlidePart.SlideLayoutPart)
{
slidePart.AddPart(lastSlidePart.SlideLayoutPart);
}
// Insert the new slide into the slide list after the previous slide.
SlideId newSlideId = slideIdList.InsertAfter(new SlideId(), prevSlideId);
newSlideId.Id = maxSlideId;
newSlideId.RelationshipId = presentationPart.GetIdOfPart(slidePart);
// Save the modified presentation.
presentationPart.Presentation.Save();
}
' Create the slide part for the new slide.
Dim slidePart As SlidePart = presentationPart.AddNewPart(Of SlidePart)()
' Save the new slide part.
slide.Save(slidePart)
' Modify the slide ID list in the presentation part.
' The slide ID list should not be null.
Dim slideIdList As SlideIdList = presentationPart.Presentation.SlideIdList
' Find the highest slide ID in the current list.
Dim maxSlideId As UInteger = 1
Dim prevSlideId As SlideId = Nothing
For Each slideId As SlideId In slideIdList.ChildElements
If slideId.Id > maxSlideId Then
maxSlideId = slideId.Id
End If
position -= 1
If position = 0 Then
prevSlideId = slideId
End If
Next slideId
maxSlideId += 1
' Get the ID of the previous slide.
Dim lastSlidePart As SlidePart
If prevSlideId IsNot Nothing Then
lastSlidePart = CType(presentationPart.GetPartById(prevSlideId.RelationshipId), SlidePart)
Else
lastSlidePart = CType(presentationPart.GetPartById((CType(slideIdList.ChildElements(0), SlideId)).RelationshipId), SlidePart)
End If
' Use the same slide layout as that of the previous slide.
If Nothing IsNot lastSlidePart.SlideLayoutPart Then
slidePart.AddPart(lastSlidePart.SlideLayoutPart)
End If
' Insert the new slide into the slide list after the previous slide.
Dim newSlideId As SlideId = slideIdList.InsertAfter(New SlideId(), prevSlideId)
newSlideId.Id = maxSlideId
newSlideId.RelationshipId = presentationPart.GetIdOfPart(slidePart)
' Save the modified presentation.
presentationPart.Presentation.Save()
End Sub
Beispielcode
Mit dem Beispielcode können Sie einer vorhandenen Präsentation eine neue Folie hinzufügen. In Ihrem Programm können Sie den folgenden Aufruf der InsertNewSlide-Methode verwenden, um einer Präsentationsdatei namens "Myppt10.pptx" an Position 1 eine neue Folie mit dem Titel "My new slide" hinzuzufügen.
InsertNewSlide(@"C:\Users\Public\Documents\Myppt10.pptx", 1, "My new slide");
InsertNewSlide("C:\Users\Public\Documents\Myppt10.pptx", 1, "My new slide")
Nachdem Sie das Programm ausgeführt haben, wird die neue Folie als zweite Folie in der Präsentation angezeigt.
Nachstehend ist der vollständige Beispielcode in C# und Visual Basic aufgeführt.
// Insert a slide into the specified presentation.
public static void InsertNewSlide(string presentationFile, int position, string slideTitle)
{
// Open the source document as read/write.
using (PresentationDocument presentationDocument = PresentationDocument.Open(presentationFile, true))
{
// Pass the source document and the position and title of the slide to be inserted to the next method.
InsertNewSlide(presentationDocument, position, slideTitle);
}
}
// Insert the specified slide into the presentation at the specified position.
public static void InsertNewSlide(PresentationDocument presentationDocument, int position, string slideTitle)
{
if (presentationDocument == null)
{
throw new ArgumentNullException("presentationDocument");
}
if (slideTitle == null)
{
throw new ArgumentNullException("slideTitle");
}
PresentationPart presentationPart = presentationDocument.PresentationPart;
// Verify that the presentation is not empty.
if (presentationPart == null)
{
throw new InvalidOperationException("The presentation document is empty.");
}
// Declare and instantiate a new slide.
Slide slide = new Slide(new CommonSlideData(new ShapeTree()));
uint drawingObjectId = 1;
// Construct the slide content.
// Specify the non-visual properties of the new slide.
NonVisualGroupShapeProperties nonVisualProperties = slide.CommonSlideData.ShapeTree.AppendChild(new NonVisualGroupShapeProperties());
nonVisualProperties.NonVisualDrawingProperties = new NonVisualDrawingProperties() { Id = 1, Name = "" };
nonVisualProperties.NonVisualGroupShapeDrawingProperties = new NonVisualGroupShapeDrawingProperties();
nonVisualProperties.ApplicationNonVisualDrawingProperties = new ApplicationNonVisualDrawingProperties();
// Specify the group shape properties of the new slide.
slide.CommonSlideData.ShapeTree.AppendChild(new GroupShapeProperties());
// Declare and instantiate the title shape of the new slide.
Shape titleShape = slide.CommonSlideData.ShapeTree.AppendChild(new Shape());
drawingObjectId++;
// Specify the required shape properties for the title shape.
titleShape.NonVisualShapeProperties = new NonVisualShapeProperties
(new NonVisualDrawingProperties() { Id = drawingObjectId, Name = "Title" },
new NonVisualShapeDrawingProperties(new Drawing.ShapeLocks() { NoGrouping = true }),
new ApplicationNonVisualDrawingProperties(new PlaceholderShape() { Type = PlaceholderValues.Title }));
titleShape.ShapeProperties = new ShapeProperties();
// Specify the text of the title shape.
titleShape.TextBody = new TextBody(new Drawing.BodyProperties(),
new Drawing.ListStyle(),
new Drawing.Paragraph(new Drawing.Run(new Drawing.Text() { Text = slideTitle })));
// Declare and instantiate the body shape of the new slide.
Shape bodyShape = slide.CommonSlideData.ShapeTree.AppendChild(new Shape());
drawingObjectId++;
// Specify the required shape properties for the body shape.
bodyShape.NonVisualShapeProperties = new NonVisualShapeProperties(new NonVisualDrawingProperties() { Id = drawingObjectId, Name = "Content Placeholder" },
new NonVisualShapeDrawingProperties(new Drawing.ShapeLocks() { NoGrouping = true }),
new ApplicationNonVisualDrawingProperties(new PlaceholderShape() { Index = 1 }));
bodyShape.ShapeProperties = new ShapeProperties();
// Specify the text of the body shape.
bodyShape.TextBody = new TextBody(new Drawing.BodyProperties(),
new Drawing.ListStyle(),
new Drawing.Paragraph());
// Create the slide part for the new slide.
SlidePart slidePart = presentationPart.AddNewPart<SlidePart>();
// Save the new slide part.
slide.Save(slidePart);
// Modify the slide ID list in the presentation part.
// The slide ID list should not be null.
SlideIdList slideIdList = presentationPart.Presentation.SlideIdList;
// Find the highest slide ID in the current list.
uint maxSlideId = 1;
SlideId prevSlideId = null;
foreach (SlideId slideId in slideIdList.ChildElements)
{
if (slideId.Id > maxSlideId)
{
maxSlideId = slideId.Id;
}
position--;
if (position == 0)
{
prevSlideId = slideId;
}
}
maxSlideId++;
// Get the ID of the previous slide.
SlidePart lastSlidePart;
if (prevSlideId != null)
{
lastSlidePart = (SlidePart)presentationPart.GetPartById(prevSlideId.RelationshipId);
}
else
{
lastSlidePart = (SlidePart)presentationPart.GetPartById(((SlideId)(slideIdList.ChildElements[0])).RelationshipId);
}
// Use the same slide layout as that of the previous slide.
if (null != lastSlidePart.SlideLayoutPart)
{
slidePart.AddPart(lastSlidePart.SlideLayoutPart);
}
// Insert the new slide into the slide list after the previous slide.
SlideId newSlideId = slideIdList.InsertAfter(new SlideId(), prevSlideId);
newSlideId.Id = maxSlideId;
newSlideId.RelationshipId = presentationPart.GetIdOfPart(slidePart);
// Save the modified presentation.
presentationPart.Presentation.Save();
}
' Insert a slide into the specified presentation.
Public Sub InsertNewSlide(ByVal presentationFile As String, ByVal position As Integer, ByVal slideTitle As String)
' Open the source document as read/write.
Dim presentationDocument As PresentationDocument = presentationDocument.Open(presentationFile, True)
Using (presentationDocument)
'Pass the source document and the position and title of the slide to be inserted to the next method.
InsertNewSlide(presentationDocument, position, slideTitle)
End Using
End Sub
' Insert a slide into the specified presentation.
Public Sub InsertNewSlide(ByVal presentationDocument As PresentationDocument, ByVal position As Integer, ByVal slideTitle As String)
If (presentationDocument Is Nothing) Then
Throw New ArgumentNullException("presentationDocument")
End If
If (slideTitle Is Nothing) Then
Throw New ArgumentNullException("slideTitle")
End If
Dim presentationPart As PresentationPart = presentationDocument.PresentationPart
' Verify that the presentation is not empty.
If (presentationPart Is Nothing) Then
Throw New InvalidOperationException("The presentation document is empty.")
End If
' Declare and instantiate a new slide.
Dim slide As Slide = New Slide(New CommonSlideData(New ShapeTree))
Dim drawingObjectId As UInteger = 1
' Construct the slide content.
' Specify the non-visual properties of the new slide.
Dim nonVisualProperties As DocumentFormat.OpenXml.Presentation.NonVisualGroupShapeProperties = slide.CommonSlideData.ShapeTree.AppendChild(New _
DocumentFormat.OpenXml.Presentation.NonVisualGroupShapeProperties())
nonVisualProperties.NonVisualDrawingProperties = New DocumentFormat.OpenXml.Presentation.NonVisualDrawingProperties() With {.Id = 1, .Name = ""}
nonVisualProperties.NonVisualGroupShapeDrawingProperties = New DocumentFormat.OpenXml.Presentation.NonVisualGroupShapeDrawingProperties()
nonVisualProperties.ApplicationNonVisualDrawingProperties = New ApplicationNonVisualDrawingProperties()
' Specify the group shape properties of the new slide.
slide.CommonSlideData.ShapeTree.AppendChild(New DocumentFormat.OpenXml.Presentation.GroupShapeProperties())
' Declare and instantiate the title shape of the new slide.
Dim titleShape As DocumentFormat.OpenXml.Presentation.Shape = slide.CommonSlideData.ShapeTree.AppendChild _
(New DocumentFormat.OpenXml.Presentation.Shape())
drawingObjectId = (drawingObjectId + 1)
' Specify the required shape properties for the title shape.
titleShape.NonVisualShapeProperties = New DocumentFormat.OpenXml.Presentation.NonVisualShapeProperties(New _
DocumentFormat.OpenXml.Presentation.NonVisualDrawingProperties() With {.Id = drawingObjectId, .Name = "Title"}, _
New DocumentFormat.OpenXml.Presentation.NonVisualShapeDrawingProperties _
(New Drawing.ShapeLocks() With {.NoGrouping = True}), _
New ApplicationNonVisualDrawingProperties(New PlaceholderShape() With {.Type = PlaceholderValues.Title}))
titleShape.ShapeProperties = New DocumentFormat.OpenXml.Presentation.ShapeProperties()
' Specify the text of the title shape.
titleShape.TextBody = New DocumentFormat.OpenXml.Presentation.TextBody(New Drawing.BodyProperties, _
New Drawing.ListStyle, New Drawing.Paragraph _
(New Drawing.Run(New Drawing.Text() With {.Text = slideTitle})))
' Declare and instantiate the body shape of the new slide.
Dim bodyShape As DocumentFormat.OpenXml.Presentation.Shape = slide.CommonSlideData.ShapeTree.AppendChild _
(New DocumentFormat.OpenXml.Presentation.Shape())
drawingObjectId = (drawingObjectId + 1)
' Specify the required shape properties for the body shape.
bodyShape.NonVisualShapeProperties = New NonVisualShapeProperties(New NonVisualDrawingProperties() With {.Id = drawingObjectId, .Name = "ContentPlaceholder"}, _
New NonVisualShapeDrawingProperties(New Drawing.ShapeLocks() With {.NoGrouping = True}), _
New ApplicationNonVisualDrawingProperties(New PlaceholderShape() With {.Index = 1}))
bodyShape.ShapeProperties = New ShapeProperties()
' Specify the text of the body shape.
bodyShape.TextBody = New TextBody(New Drawing.BodyProperties, New Drawing.ListStyle, New Drawing.Paragraph)
' Create the slide part for the new slide.
Dim slidePart As SlidePart = presentationPart.AddNewPart(Of SlidePart)()
' Save the new slide part.
slide.Save(slidePart)
' Modify the slide ID list in the presentation part.
' The slide ID list should not be null.
Dim slideIdList As SlideIdList = presentationPart.Presentation.SlideIdList
' Find the highest slide ID in the current list.
Dim maxSlideId As UInteger = 1
Dim prevSlideId As SlideId = Nothing
For Each slideId As SlideId In slideIdList.ChildElements
If (CType(slideId.Id, UInteger) > maxSlideId) Then
maxSlideId = slideId.Id
End If
position = (position - 1)
If (position = 0) Then
prevSlideId = slideId
End If
Next
maxSlideId = (maxSlideId + 1)
' Get the ID of the previous slide.
Dim lastSlidePart As SlidePart = Nothing
If (Not prevSlideId Is Nothing) Then
lastSlidePart = CType(presentationPart.GetPartById(prevSlideId.RelationshipId), SlidePart)
Else
lastSlidePart = CType(presentationPart.GetPartById(CType(slideIdList.ChildElements(0), SlideId).RelationshipId), SlidePart)
End If
' Use the same slide layout as that of the previous slide.
If (Not (lastSlidePart.SlideLayoutPart) Is Nothing) Then
slidePart.AddPart(lastSlidePart.SlideLayoutPart)
End If
' Insert the new slide into the slide list after the previous slide.
Dim newSlideId As SlideId = slideIdList.InsertAfter(New SlideId, prevSlideId)
newSlideId.Id = maxSlideId
newSlideId.RelationshipId = presentationPart.GetIdOfPart(slidePart)
' Save the modified presentation.
presentationPart.Presentation.Save()
End Sub