[方法] 新しいスライドをプレゼンテーションに挿入する (Open XML SDK)How to: Insert a new slide into a presentation (Open XML SDK)

このトピックでは、Open XML SDK 2.5 のクラスを使用して、プログラムによってプレゼンテーションに新しいスライドを挿入する方法について説明します。This topic shows how to use the classes in the Open XML SDK 2.5 to insert a new slide into a presentation programmatically.

このトピックのコードをコンパイルするには、次のアセンブリ ディレクティブが必要です。The following assembly directives are required to compile the code in this topic.

    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

PresentationDocument オブジェクトを取得するGetting a PresentationDocument Object

Open XML SDK では、PresentationDocument クラスがプレゼンテーション ドキュメント パッケージを表します。In the Open XML SDK, the PresentationDocument class represents a presentation document package. プレゼンテーション ドキュメントを操作するには、最初に PresentationDocument クラスのインスタンスを作成し、次にそのインスタンスを操作します。To work with a presentation document, first create an instance of the PresentationDocument class, and then work with that instance. ドキュメントからクラスのインスタンスを作成するには、Open(String, Boolean) メソッドを呼び出します。このメソッドは、ファイル パスの他に、2 つ目のパラメーターとしてブール値を使用して、ドキュメントが編集可能かどうかを指定します。To create the class instance from the document call the Open(String, Boolean) method that uses a file path, and a Boolean value as the second parameter to specify whether a document is editable. 読み取り/書き込み用にドキュメントを開くには、次の using ステートメントに示すように、このパラメーターの値を true に指定します。To open a document for read/write, specify the value true for this parameter as shown in the following using statement. このコード セグメントでは、presentationFile パラメーターの文字列はドキュメントを開く元のファイルへの完全なパスを表します。In this code segment, the presentationFile parameter is a string that represents the full path for the file from which you want to open the document.

    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

using ステートメントは、一般的な .Open, .Save, .Close シーケンスの推奨される代替手段を提供します。これによって、閉じかっこに達したときに、 Dispose メソッド (Open XML SDK がリソースをクリーンアップするために使用する内部メソッド) が自動的に呼び出されます。 using ステートメントに続くブロックは、作成された、または using ステートメントで指定されたオブジェクト (この場合は presentationDocument) のスコープを設定します。The using statement provides a recommended alternative to the typical .Open, .Save, .Close sequence. It ensures that the Dispose method (internal method used by the Open XML SDK to clean up resources) is automatically called when the closing brace is reached. The block that follows the using statement establishes a scope for the object that is created or named in the using statement, in this case presentationDocument.

プレゼンテーション ドキュメントの基本構造Basic Presentation Document Structure

PresentationML ドキュメントの基本構造は、プレゼンテーション定義を含むメイン パーツで構成されます。The basic document structure of a PresentationML document consists of the main part that contains the presentation definition. ISO/IEC 29500 仕様書では、PresentationML パッケージの全体的なフォームについて次のように説明しています。The following text from the ISO/IEC 29500 specification introduces the overall form of a PresentationML package.

PresentationML パッケージのメイン パーツは、プレゼンテーションのルート要素から始まります。A PresentationML package's main part starts with a presentation root element. この要素にはプレゼンテーションが含まれており、プレゼンテーションは スライド リスト、スライド マスター リスト、ノート マスター リスト、配布資料マスター リストを参照します。That element contains a presentation, which, in turn, refers to a slide list, a slide master list, a notes master list, and a handout master list. スライド リストはプレゼンテーション内のすべてのスライドを参照します。スライド マスター リストはプレゼンテーションで使用されるスライド マスター全体を参照します。ノート マスターにはノート ページの書式設定に関する情報が含まれます。配布資料マスターは配布資料がどのように表示されるかを示します。The slide list refers to all of the slides in the presentation; the slide master list refers to the entire slide masters used in the presentation; the notes master contains information about the formatting of notes pages; and the handout master describes how a handout looks.

配布資料とは、聴衆が後で参照できるように一連のスライドを印刷したものです。A handout is a printed set of slides that can be provided to an audience for future reference.

テキストやグラフィックのように、各スライドにはコメントノートを含めることができ、レイアウトを指定したり、1 つ以上のカスタム プレゼンテーションに組み込んだりできます。As well as text and graphics, each slide can contain comments and notes, can have a layout, and can be part of one or more custom presentations. (コメントは、プレゼンテーション スライド デッキを管理するユーザー向けの注釈です。(A comment is an annotation intended for the person maintaining the presentation slide deck. ノートは、発表者または聴衆向けのリマインダーまたはテキストの一部です)。A note is a reminder or piece of text intended for the presenter or the audience.)

PresentationML ドキュメントに含めることができるその他の機能には、アニメーションオーディオビデオ、スライド間の画面切り替え効果があります。Other features that a PresentationML document can include the following: animation, audio, video, and transitions between slides.

PresentationML ドキュメントは、単一のパーツ内の 1 つの大きな本体としては格納されません。その代わりに、特定のグループの機能を実現する要素が別々のパーツに格納されます。たとえば、ドキュメント内のすべてのコメントが 1 つのコメント パーツに格納される一方で、各スライドは自分のパーツを持ちます。A PresentationML document is not stored as one large body in a single part. Instead, the elements that implement certain groupings of functionality are stored in separate parts. For example, all comments in a document are stored in one comment part while each slide has its own part.

© ISO/IEC29500: 2008.© ISO/IEC29500: 2008.

次の XML コードは、267 と 256 という Id で示される 2 つのスライドを含むプレゼンテーションを表します。The following XML code segment represents a presentation that contains two slides denoted by the Id's 267 and 256.

    <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>

Open XML SDK 2.5 を使用すると、PresentationML 要素に対応する厳密に型指定されたクラスを使用してドキュメント構造とコンテンツを作成できます。これらのクラスは、DocumentFormat.OpenXml.Presentation 名前空間にあります。次の表に、 sldsldLayoutsldMaster、および notesMaster 要素に対応するクラスのクラス名を示します。Using the Open XML SDK 2.5, you can create document structure and content using strongly-typed classes that correspond to PresentationML elements. You can find these classes in the DocumentFormat.OpenXml.Presentation namespace. The following table lists the class names of the classes that correspond to the sld, sldLayout, sldMaster, and notesMaster elements:

PresentationML の要素PresentationML Element Open XML SDK 2.5 のクラスOpen XML SDK 2.5 Class 説明Description
sldsld SlideSlide プレゼンテーション スライド。SlidePart のルート要素Presentation Slide. It is the root element of SlidePart.
sldLayoutsldLayout SlideLayoutSlideLayout スライド レイアウト。SlideLayoutPart のルート要素Slide Layout. It is the root element of SlideLayoutPart.
sldMastersldMaster SlideMasterSlideMaster スライド マスター。SlideMasterPart のルート要素Slide Master. It is the root element of SlideMasterPart.
notesMasternotesMaster NotesMasterNotesMaster ノート マスター (または handoutMaster)。NotesMasterPart のルート要素Notes Master (or handoutMaster). It is the root element of NotesMasterPart.

サンプル コードの動作のしくみHow the Sample Code Works

このサンプル コードは、 InsertNewSlide メソッドの 2 つのオーバーロードで構成されます。最初のオーバーロード メソッドへの 3 つのパラメーターとして、スライドを追加するプレゼンテーション ファイルの完全パス、0 から始まるスライドのインデックス位置 (プレゼンテーション内のスライドを追加する位置を示す) を表す整数、および新しいスライドのタイトルを表す文字列を渡します。ここでは、プレゼンテーション ファイルを読み取り/書き込み用として開き、 PresentationDocument オブジェクトを取得し、そのオブジェクトを 2 番目のオーバーロードされた InsertNewSlide メソッドに渡して挿入します。The sample code consists of two overloads of the InsertNewSlide method. The first overloaded method takes three parameters: the full path to the presentation file to which to add a slide, an integer that represents the zero-based slide index position in the presentation where to add the slide, and the string that represents the title of the new slide. It opens the presentation file as read/write, gets a PresentationDocument object, and then passes that object to the second overloaded InsertNewSlide method, which performs the insertion.

    // 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

2 番目のオーバーロードされた InsertNewSlide メソッドは、新しい Slide オブジェクトを作成し、そのプロパティを設定して、そのオブジェクトをプレゼンテーション内のスライド順に挿入します。このメソッドの最初のセクションでは、スライドを作成し、そのプロパティを設定します。The second overloaded InsertNewSlide method creates a new Slide object, sets its properties, and then inserts it into the slide order in the presentation. The first section of the method creates the slide and sets its properties.

    // 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())

2 番目のオーバーロードされた InsertNewSlide メソッドの次のセクションでは、タイトルの図形をスライドに追加し、テキストなどのプロパティを設定します。The next section of the second overloaded InsertNewSlide method adds a title shape to the slide and sets its properties, including its text

    // 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})))

2 番目のオーバーロードされた InsertNewSlide メソッドの次のセクションでは、本文の図形をスライドに追加して、そのプロパティ (テキストなど) を設定します。The next section of the second overloaded InsertNewSlide method adds a body shape to the slide and sets its properties, including its text.

    // 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())

2 番目のオーバーロードされた InsertNewSlide メソッドの最後のセクションでは、新しいスライド パーツを作成し、スライドを挿入する指定されたインデックス位置を見つけて、そのパーツを挿入し、変更したプレゼンテーションを保存します。The final section of the second overloaded InsertNewSlide method creates a new slide part, finds the specified index position where to insert the slide, and then inserts it and saves the modified presentation.

    // 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

サンプル コードSample Code

サンプル コードを使用して、既存のプレゼンテーションに新しいスライドを追加できます。このプログラム内では、次のように InsertNewSlide メソッドを呼び出して、"Myppt10.pptx" という名前のプレゼンテーション ファイルのポジション 1 に、"My new slide" というタイトルの新しいスライドを追加できます。By using the sample code you can add a new slide to an existing presentation. In your program, you can use the following call to the InsertNewSlide method to add a new slide to a presentation file named "Myppt10.pptx," with the title "My new slide," at position 1.

    InsertNewSlide(@"C:\Users\Public\Documents\Myppt10.pptx", 1, "My new slide");
    InsertNewSlide("C:\Users\Public\Documents\Myppt10.pptx", 1, "My new slide")

プログラムを実行した後、新しいスライドがプレゼンテーションの 2 番目のスライドとして表示されます。After you have run the program, the new slide would show up as the second slide in the presentation.

以下に、C# と Visual Basic による完全なサンプル コードを示します。The following is the complete sample code in both C# and Visual Basic.

    // 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

関連項目See also

その他のリソースOther resources

Open XML SDK 2.5 クラス ライブラリ リファレンスOpen XML SDK 2.5 class library reference