次の方法で共有


PowerPoint アドイン

PowerPoint アドインを使用して Windows、iPad、Mac、およびブラウザー上など、複数のプラットフォームでのユーザーのプレゼンテーション用に魅力的なソリューションを構築できます。 次の 2 種類の PowerPoint アドインを作成できます。

  • 作業ウィンドウ アドインを使えば、サービスを介して、参照情報を取り込んだり、プレゼンテーションにデータを挿入したりすることができます。 たとえば Pexels - 無料ストックフォト アドインでは、これを使ってプロの写真をプレゼンテーションに追加することができます。 独自の作業ウィンドウ アドインを作成するには、「 最初のPowerPoint作業ウィンドウ アドインをビルドする」から始めることができます。

  • コンテンツ アドインを使うと、プレゼンテーションに HTML5 の動的コンテンツが追加されます。 たとえば、PowerPointアドインの LucidChart ダイアグラム を参照してください。このアドインでは、LucidChart の対話型ダイアグラムがデッキに挿入されます。 独自のコンテンツ アドインを作成するには、「 最初のPowerPoint コンテンツ アドインをビルドする」から始めます。

PowerPoint アドインのシナリオ

この記事のコード例では、PowerPoint用のアドインを開発するときに役立つ基本的なタスクをいくつか示します。

新しいスライドを追加し、そのスライドに移動します

次のコード サンプルでは、 addAndNavigateToNewSlide 関数は SlideCollection.add メソッドを呼び出して、プレゼンテーションに新しいスライドを追加します。 次に、この関数は Presentation.setSelectedSlides メソッドを呼び出して、新しいスライドに移動します。

async function addAndNavigateToNewSlide() {
  // Adds a new slide then navigates to it.
  await PowerPoint.run(async (context) => {
    const slideCountResult = context.presentation.slides.getCount();
    context.presentation.slides.add();
    await context.sync();

    const newSlide = context.presentation.slides.getItemAt(slideCountResult.value);
    newSlide.load("id");
    await context.sync();

    console.log(`Added slide - ID: ${newSlide.id}`);

    // Navigate to the new slide.
    context.presentation.setSelectedSlides([newSlide.id]);
    await context.sync();
  });
}

次のコード サンプルでは、 getSelectedSlides 関数は Presentation.getSelectedSlides メソッドを呼び出して、選択したスライドを取得し、その ID をログに記録します。 関数は、現在のスライド (または選択範囲の最初のスライド) に対して動作できます。

async function getSelectedSlides() {
  // Gets the ID of the current slide (or selected slides).
  await PowerPoint.run(async (context) => {
    const selectedSlides = context.presentation.getSelectedSlides();
    selectedSlides.load("items/id");
    await context.sync();

    if (selectedSlides.items.length === 0) {
      console.warn("No slides were selected.");
      return;
    }

    console.log("IDs of selected slides:");
    selectedSlides.items.forEach(item => {
      console.log(item.id);
    });

    // Navigate to first selected slide.
    const currentSlide = selectedSlides.items[0];
    console.log(`Navigating to slide with ID ${currentSlide.id} ...`);
    context.presentation.setSelectedSlides([currentSlide.id]);

    // Perform actions on current slide...
  });
}

次のコード サンプルでは、 goToSlideByIndex 関数は、 Presentation.setSelectedSlides メソッドを呼び出して、プレゼンテーションの最初のスライドに移動します。インデックスは 0 です。 このサンプルで移動できる最大スライド インデックスは、 slideCountResult.value - 1です。

async function goToSlideByIndex() {
  await PowerPoint.run(async (context) => {
    // Gets the number of slides in the presentation.
    const slideCountResult = context.presentation.slides.getCount();
    await context.sync();

    if (slideCountResult.value === 0) {
      console.warn("There are no slides.");
      return;
    }

    const slide = context.presentation.slides.getItemAt(0); // First slide
    //const slide = context.presentation.slides.getItemAt(slideCountResult.value - 1); // Last slide
    slide.load("id");
    await context.sync();

    console.log(`Slide ID: ${slide.id}`);

    // Navigate to the slide.
    context.presentation.setSelectedSlides([slide.id]);
    await context.sync();
  });
}

プレゼンテーションの URL を取得する

次のコード サンプルでは、 getFileUrl 関数は Document.getFileProperties メソッドを呼び出して、プレゼンテーション ファイルの URL を取得します。

function getFileUrl() {
  // Gets the URL of the current file.
  Office.context.document.getFilePropertiesAsync(function (asyncResult) {
    const fileUrl = asyncResult.value.url;
    if (fileUrl === "") {
      console.warn("The file hasn't been saved yet. Save the file and try again.");
    } else {
      console.log(`File URL: ${fileUrl}`);
    }
  });
}

プレゼンテーションの作成

アドインでは、アドインが現在実行されている PowerPoint のインスタンスとは異なる新しいプレゼンテーションを作成できます。 PowerPoint の名前空間には、この目的のための createPresentation メソッドがあります。 このメソッドが呼び出されると、新しいプレゼンテーションが PowerPoint の新しいインスタンスですぐに開いて表示されます。 アドインは前のプレゼンテーションで開いて実行されたままになります。

PowerPoint.createPresentation();

createPresentation メソッドでは既存のプレゼンテーションのコピーの作成もできます。 メソッドは、省略可能なパラメーターとして、.pptx ファイルの Base64 でエンコードされた文字列表現を受け取ります。 文字列の引数は有効な .pptx ファイルと見なされ、作成されるプレゼンテーションはそのファイルのコピーになります。 FileReader クラスを使用すると、次の例に示すように、ファイルを必要な Base64 でエンコードされた文字列に変換できます。

const myFile = document.getElementById("file") as HTMLInputElement;
const reader = new FileReader();

reader.onload = function (event) {
    // Strip off the metadata before the Base64-encoded string.
    const startIndex = reader.result.toString().indexOf("base64,");
    const copyBase64 = reader.result.toString().substr(startIndex + 7);

    PowerPoint.createPresentation(copyBase64);
};

// Read in the file as a data URL so we can parse the Base64-encoded string.
reader.readAsDataURL(myFile.files[0]);

HTML 実装を含む完全なコード サンプルについては、「プレゼンテーションの 作成」を参照してください。

プレゼンテーションのアクティブ ビューの検出と ActiveViewChanged イベントの処理を行う

コンテンツ アドインを構築する場合は、プレゼンテーションのアクティブなビューを取得し、Office.onReady 呼び出しの一部として Document.ActiveViewChanged イベントを処理する必要があります。

注:

PowerPoint on the webでは、スライド ショー モードは新しいセッションとして扱われるため、Document.ActiveViewChanged イベントは発生しません。 この場合、次のコード サンプルに示すように、アドインで読み込むアクティブ ビューをフェッチする必要があります。

コード サンプルについては、次の点に注意してください。

  • getActiveFileView関数は Document.getActiveViewAsync メソッドを呼び出して、プレゼンテーションの現在のビューが "編集" (標準スライド並べ替えツールアウトラインなど、スライドを編集できるビュー) または "読み取り" (スライド ショーまたは読み取りビュー) かどうかをします。
  • registerActiveViewChanged関数は Document.addHandlerAsync メソッドを呼び出して、Document.ActiveViewChanged イベントのハンドラーを登録します。
  • この例では、情報を表示するために、Visual Studio Office アドイン プロジェクト テンプレートに含まれる showNotification 関数を使用します。 Visual Studio を使用してアドインを開発していない場合は、 showNotification 関数を独自のコードに置き換える必要があります。
// General Office.onReady function. Called after the add-in loads and Office JS is initialized.
Office.onReady(() => {
  // Get whether the current view is edit or read.
  const currentView = getActiveFileView();

  // Register the active view changed handler.
  registerActiveViewChanged();

  // Render the content based off of the current view.
  if (currentView === Office.ActiveView.Read) {
      // Handle read view.
      console.log('Current view is read.');
      // You can add any specific logic for the read view here.
  } else {
      // Handle edit view.
      console.log('Current view is edit.');
      // You can add any specific logic for the edit view here.
  }
});

// Gets the active file view.
function getActiveFileView() {
    console.log('Getting active file view...');
    Office.context.document.getActiveViewAsync(function (result) {
        if (result.status === Office.AsyncResultStatus.Succeeded) {
            console.log('Active view:', result.value);
            return result.value;
        } else {
            console.error('Error getting active view:', result.error.message);
            showNotification('Error:', result.error.message);
            return null;
        }
    });
}

// Registers the ActiveViewChanged event.
function registerActiveViewChanged() {
    console.log('Registering ActiveViewChanged event handler...');
    Office.context.document.addHandlerAsync(
        Office.EventType.ActiveViewChanged,
        activeViewHandler,
        function (result) {
            if (result.status === Office.AsyncResultStatus.Failed) {
                console.error('Failed to register active view changed handler:', result.error.message);
                showNotification('Error:', result.error.message);
            } else {
                console.log('Active view changed handler registered successfully.');
            }
        });
}

// ActiveViewChanged event handler.
function activeViewHandler(eventArgs) {
    console.log('Active view changed:', JSON.stringify(eventArgs));
    showNotification('Active view changed', `The active view has changed to: ${eventArgs.activeView}`);
    // You can add logic here based on the new active view.
}

関連項目