次の方法で共有


プレゼンテーション内のスライド間の切り替えを追加する

このトピックでは、Open XML SDK のクラスを使用して、プレゼンテーション内のすべてのスライド間に切り替えをプログラムで追加する方法について説明します。

Presentation オブジェクトの取得

Open XML SDK では、 PresentationDocument クラスはプレゼンテーション ドキュメント パッケージを表します。 プレゼンテーション ドキュメントを操作するには、まず PresentationDocument クラスのインスタンスを作成してから、そのインスタンスを操作します。 ドキュメントからクラス インスタンスを作成するには、ファイル パスとブール値を 2 番目のパラメーターとして使用する Open メソッドを呼び出して、ドキュメントが編集可能かどうかを指定します。 読み取り/書き込みのためにドキュメントを開くには、次のusingステートメントに示すように、このパラメーターの値trueを指定します。 このコードでは、file パラメーターは、ドキュメントを開くファイルのパスを表す文字列です。

using (PresentationDocument presentationDocument = PresentationDocument.Open(filePath, true))

v3.0.0 以降では、using ステートメントに依存することを優先して、Close() メソッドが削除されました。 これにより、閉じかっこに達したときに、 Dispose() メソッドが自動的に呼び出されます。 using ステートメントに続くブロックは、using ステートメントで作成または名前付けされたオブジェクトのスコープを確立します(この場合はppt

遷移の構造

Transition 要素 <transition> は、前のスライドから現在のスライドに切り替えるために使用するスライド切り替えの種類を指定します。 つまり、切り替え情報は切り替え完了後に表示されるスライドに格納されます。

次の表に、遷移の属性とそれぞれの説明を示します。

属性 説明
advClick (クリックすると進む) マウス クリックでスライドを進めるかどうかを指定します。 この属性が指定されていない場合は、true の値が想定されます。
advTm (時間の経過後に進む) 遷移を開始する時間をミリ秒単位で指定します。 この設定は、advClick 属性と組み合わせて使用できます。 この属性が指定されていない場合は、自動進が発生しないと見なされます。
spd (遷移速度) 現在のスライドから次のスライドに切り替えるときに使用する切り替え速度を指定します。

[: 次の例を考えてみましょう

      <p:transition spd="slow" advClick="1" advTm="3000">
        <p:randomBar dir="horz"/>
      </p:transition>

上記の例では、遷移速度 <speed> が低速に設定されています (使用可能なオプション: 低速、med、fast)。 [クリック <advClick> の進み] が true に設定され、時間 <advTm> が 3000 ミリ秒に設定された後に進みます。 Random Bar 子要素 <randomBar> は、ランダムに配置された水平方向の <dir="horz"> または新しいスライドが完全に表示されるまで追加され続けるスライド上の垂直 <dir="vert"> バーのセットを使用する randomBar スライド切り替え効果を記述します。 例終わり]

Transition の子要素の完全な一覧は、次のように表示できます。 Transition

代替コンテンツの構造

Office Open XML は、OFFICE Open XML 形式を利用する将来のソフトウェア アプリケーションによって開発された拡張機能など、ISO/IEC 29500 Office Open XML 仕様で定義されていないコンテンツを格納するためのメカニズムを定義します。 このメカニズムを使用すると、コンテンツの一連の代替表現を格納できます。そこから、使用するアプリケーションは、要件を満たす最初の代替手段を使用できます。

切り替えの期間を指定することを目的とした新しい遷移オブジェクトを作成するアプリケーションを考えてみましょう。 この機能は、Office Open XML 仕様では定義されていません。 次のように AlternateContent ブロックを使用すると、期間をミリ秒単位で <p14:dur> 指定できます。

[:

  <mc:AlternateContent xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
   xmlns:p14="http://schemas.microsoft.com/office/powerpoint/2010/main">
    <mc:Choice Requires="p14">
      <p:transition spd="slow" p14:dur="2000" advClick="1" advTm="3000">
        <p:randomBar/>
      </p:transition>
    </mc:Choice>
    <mc:Fallback>
      <p:transition spd="slow" advClick="1" advTm="3000">
        <p:randomBar/>
      </p:transition>
    </mc:Fallback>
  </mc:AlternateContent>

上記の例の Choice 要素では、遷移の期間を指定するために dur 属性が必要です。また、フォールバック要素を使用すると、この名前空間をサポートしていないクライアントは適切な代替表現を表示できます。 例終わり]

P14 クラスの詳細については、こちらを参照してください。 P14

サンプル コードの動作のしくみ

using ステートメントで読み取り/書き込みアクセスを指定してプレゼンテーション ファイルを開くと、プレゼンテーション ドキュメントからプレゼンテーション パーツが取得されます。 次に、プレゼンテーション内のすべてのスライドのリレーションシップ ID を取得し、リレーションシップ ID からスライド パーツを取得します。 次に、コードはスライドに設定されている既存の遷移がないかどうかを確認し、それらを新しい RandomBarTransition に置き換えます。

   // Define the transition start time and duration in milliseconds
   string startTransitionAfterMs = "3000", durationMs = "2000";

   // Set to true if you want to advance to the next slide on mouse click
   bool advanceOnClick = true;

   // Iterate through each slide ID to get slides parts
   foreach (SlideId slideId in slidesIds)
   {
       // Get the relationship ID of the slide
       string? relId = slideId!.RelationshipId!.ToString();

       if (relId == null)
       {
           throw new NullReferenceException("RelationshipId not found");
       }

       // Get the slide part using the relationship ID
       SlidePart? slidePart = (SlidePart)presentationDocument.PresentationPart.GetPartById(relId);

       // Remove existing transitions if any
       if (slidePart.Slide.Transition != null)
       {
           slidePart.Slide.Transition.Remove();
       }

       // Check if there are any AlternateContent elements
       if (slidePart!.Slide.Descendants<AlternateContent>().ToList().Count > 0)
       {
           // Get all AlternateContent elements
           List<AlternateContent> alternateContents = [.. slidePart.Slide.Descendants<AlternateContent>()];
           foreach (AlternateContent alternateContent in alternateContents)
           {
               // Remove transitions in AlternateContentChoice within AlternateContent
               List<OpenXmlElement> childElements = alternateContent.ChildElements.ToList();

               foreach (OpenXmlElement element in childElements)
               {
                   List<Transition> transitions = element.Descendants<Transition>().ToList();
                   foreach (Transition transition in transitions)
                   {
                       transition.Remove();
                   }
               }
               // Add new transitions to AlternateContentChoice and AlternateContentFallback
               alternateContent!.GetFirstChild<AlternateContentChoice>();
               Transition choiceTransition = new Transition(new RandomBarTransition()) { Duration = durationMs, AdvanceAfterTime = startTransitionAfterMs, AdvanceOnClick = advanceOnClick, Speed = TransitionSpeedValues.Slow };
               Transition fallbackTransition = new Transition(new RandomBarTransition()) {AdvanceAfterTime = startTransitionAfterMs, AdvanceOnClick = advanceOnClick, Speed = TransitionSpeedValues.Slow };
               alternateContent!.GetFirstChild<AlternateContentChoice>()!.Append(choiceTransition);
               alternateContent!.GetFirstChild<AlternateContentFallback>()!.Append(fallbackTransition);
           }
       }

現在スライドに切り替えがない場合、コードによって新しい遷移が作成されます。 どちらの場合もフォールバック遷移として RandomBarTransition が使用されますが、この名前空間をサポートしていないクライアントに対する grater サポートを許可するために、 P14:dur(duration) は使用されません

// Add transition if there is none
else
{
    // Check if there is a transition appended to the slide and set it to null
    if (slidePart.Slide.Transition != null)
    {
        slidePart.Slide.Transition = null;
    }
    // Create a new AlternateContent element
    AlternateContent alternateContent = new AlternateContent();
    alternateContent.AddNamespaceDeclaration("mc", "http://schemas.openxmlformats.org/markup-compatibility/2006");

    // Create a new AlternateContentChoice element and add the transition
    AlternateContentChoice alternateContentChoice = new AlternateContentChoice() { Requires = "p14" };
    Transition choiceTransition = new Transition(new RandomBarTransition()) { Duration = durationMs, AdvanceAfterTime = startTransitionAfterMs, AdvanceOnClick = advanceOnClick, Speed = TransitionSpeedValues.Slow };
    Transition fallbackTransition = new Transition(new RandomBarTransition()) { AdvanceAfterTime = startTransitionAfterMs, AdvanceOnClick = advanceOnClick, Speed = TransitionSpeedValues.Slow };
    alternateContentChoice.Append(choiceTransition);

    // Create a new AlternateContentFallback element and add the transition
    AlternateContentFallback alternateContentFallback = new AlternateContentFallback(fallbackTransition);
    alternateContentFallback.AddNamespaceDeclaration("a14", "http://schemas.microsoft.com/office/drawing/2010/main");
    alternateContentFallback.AddNamespaceDeclaration("p16", "http://schemas.microsoft.com/office/powerpoint/2015/main");
    alternateContentFallback.AddNamespaceDeclaration("adec", "http://schemas.microsoft.com/office/drawing/2017/decorative");
    alternateContentFallback.AddNamespaceDeclaration("a16", "http://schemas.microsoft.com/office/drawing/2014/main");

    // Append the AlternateContentChoice and AlternateContentFallback to the AlternateContent
    alternateContent.Append(alternateContentChoice);
    alternateContent.Append(alternateContentFallback);
    slidePart.Slide.Append(alternateContent);
} 

サンプル コード

すべてのスライドに RandomBarTransition を追加するために使用できる完全なサンプル コードを次に示します。

AddTransmitionToSlides(args[0]);
static void AddTransmitionToSlides(string filePath)
{
    using (PresentationDocument presentationDocument = PresentationDocument.Open(filePath, true))
    {
    
     // Check if the presentation part and slide list are available
        if (presentationDocument.PresentationPart == null || presentationDocument.PresentationPart.Presentation.SlideIdList == null)
        {
            throw new NullReferenceException("Presentation part is empty or there are no slides");
        }

        // Get the presentation part
        PresentationPart presentationPart = presentationDocument.PresentationPart;

        // Get the list of slide IDs
        OpenXmlElementList slidesIds = presentationPart.Presentation.SlideIdList.ChildElements;

        // Define the transition start time and duration in milliseconds
        string startTransitionAfterMs = "3000", durationMs = "2000";

        // Set to true if you want to advance to the next slide on mouse click
        bool advanceOnClick = true;
     
        // Iterate through each slide ID to get slides parts
        foreach (SlideId slideId in slidesIds)
        {
            // Get the relationship ID of the slide
            string? relId = slideId!.RelationshipId!.ToString();

            if (relId == null)
            {
                throw new NullReferenceException("RelationshipId not found");
            }

            // Get the slide part using the relationship ID
            SlidePart? slidePart = (SlidePart)presentationDocument.PresentationPart.GetPartById(relId);

            // Remove existing transitions if any
            if (slidePart.Slide.Transition != null)
            {
                slidePart.Slide.Transition.Remove();
            }

            // Check if there are any AlternateContent elements
            if (slidePart!.Slide.Descendants<AlternateContent>().ToList().Count > 0)
            {
                // Get all AlternateContent elements
                List<AlternateContent> alternateContents = [.. slidePart.Slide.Descendants<AlternateContent>()];
                foreach (AlternateContent alternateContent in alternateContents)
                {
                    // Remove transitions in AlternateContentChoice within AlternateContent
                    List<OpenXmlElement> childElements = alternateContent.ChildElements.ToList();

                    foreach (OpenXmlElement element in childElements)
                    {
                        List<Transition> transitions = element.Descendants<Transition>().ToList();
                        foreach (Transition transition in transitions)
                        {
                            transition.Remove();
                        }
                    }
                    // Add new transitions to AlternateContentChoice and AlternateContentFallback
                    alternateContent!.GetFirstChild<AlternateContentChoice>();
                    Transition choiceTransition = new Transition(new RandomBarTransition()) { Duration = durationMs, AdvanceAfterTime = startTransitionAfterMs, AdvanceOnClick = advanceOnClick, Speed = TransitionSpeedValues.Slow };
                    Transition fallbackTransition = new Transition(new RandomBarTransition()) {AdvanceAfterTime = startTransitionAfterMs, AdvanceOnClick = advanceOnClick, Speed = TransitionSpeedValues.Slow };
                    alternateContent!.GetFirstChild<AlternateContentChoice>()!.Append(choiceTransition);
                    alternateContent!.GetFirstChild<AlternateContentFallback>()!.Append(fallbackTransition);
                }
            }
            
            // Add transition if there is none
            else
            {
                // Check if there is a transition appended to the slide and set it to null
                if (slidePart.Slide.Transition != null)
                {
                    slidePart.Slide.Transition = null;
                }
                // Create a new AlternateContent element
                AlternateContent alternateContent = new AlternateContent();
                alternateContent.AddNamespaceDeclaration("mc", "http://schemas.openxmlformats.org/markup-compatibility/2006");

                // Create a new AlternateContentChoice element and add the transition
                AlternateContentChoice alternateContentChoice = new AlternateContentChoice() { Requires = "p14" };
                Transition choiceTransition = new Transition(new RandomBarTransition()) { Duration = durationMs, AdvanceAfterTime = startTransitionAfterMs, AdvanceOnClick = advanceOnClick, Speed = TransitionSpeedValues.Slow };
                Transition fallbackTransition = new Transition(new RandomBarTransition()) { AdvanceAfterTime = startTransitionAfterMs, AdvanceOnClick = advanceOnClick, Speed = TransitionSpeedValues.Slow };
                alternateContentChoice.Append(choiceTransition);

                // Create a new AlternateContentFallback element and add the transition
                AlternateContentFallback alternateContentFallback = new AlternateContentFallback(fallbackTransition);
                alternateContentFallback.AddNamespaceDeclaration("a14", "http://schemas.microsoft.com/office/drawing/2010/main");
                alternateContentFallback.AddNamespaceDeclaration("p16", "http://schemas.microsoft.com/office/powerpoint/2015/main");
                alternateContentFallback.AddNamespaceDeclaration("adec", "http://schemas.microsoft.com/office/drawing/2017/decorative");
                alternateContentFallback.AddNamespaceDeclaration("a16", "http://schemas.microsoft.com/office/drawing/2014/main");

                // Append the AlternateContentChoice and AlternateContentFallback to the AlternateContent
                alternateContent.Append(alternateContentChoice);
                alternateContent.Append(alternateContentFallback);
                slidePart.Slide.Append(alternateContent);
            } 
        }
    }
}

関連項目