Share via


PowerPoint または Word 用アドインからドキュメント全体を取得する

Office アドインを作成して、PowerPoint プレゼンテーションまたは Word ドキュメントをリモートの場所に送信または発行できます。 この記事では、すべてのプレゼンテーションまたはドキュメントをデータ オブジェクトとして取得し、HTTP 要求を介してそのデータを Web サーバーに送信する、PowerPoint または Word 用の単純な作業ウィンドウ アドインを構築する方法について説明します。

PowerPoint または Word 用アドインを作成するための前提条件

この記事では、PowerPoint または Word 用の作業ウィンドウ アドインの作成にテキスト エディターを使用することを前提にしています。 作業ウィンドウ アドインを作成するには、次のファイルを作成する必要があります。

  • 共有ネットワーク フォルダーまたは Web サーバーでは、次のファイルが必要です。

    • ユーザー インターフェイスと JavaScript ファイル (Office.js およびアプリケーション固有 の .js ファイルを含む) とカスケード スタイル シート (CSS) ファイルへのリンクを含む HTML ファイル (GetDoc_App.html)。

    • アドインのプログラミング ロジックを格納する JavaScript ファイル (GetDoc_App.js)。

    • アドインのスタイルと書式設定を含む CSS ファイル (Program.css)。

  • 共有ネットワーク フォルダーまたはアドイン カタログで使用できるアドインの XML マニフェスト ファイル (GetDoc_App.xml)。 マニフェスト ファイルは、前に説明した HTML ファイルの場所を指す必要があります。

または、次のいずれかのオプションを使用して、Office アプリケーション用のアドインを作成することもできます。 必要な各ファイルと同等のファイルを更新できるため、新しいファイルを作成する必要はありません。 たとえば、Yeoman ジェネレーター オプションには、 ./src/taskpane/taskpane.html./src/taskpane/taskpane.js./src/taskpane/taskpane.css./manifest.xmlなどがあります。

作業ウィンドウ アドインを作成するために知っておくべき主要な概念

この PowerPoint または Word 用アドインの作成を開始する前に、Office アドインの作成と HTTP 要求の操作についてよく理解しておくことが必要です。 この記事では、Web サーバー上の HTTP 要求から Base64 でエンコードされたテキストをデコードする方法については説明しません。

アドインのマニフェストを作成する

Office アドインの XML マニフェスト ファイルは、アドインをホストできるアプリケーション、HTML ファイルの場所、アドインのタイトルと説明、その他の多くの特性など、アドインに関する重要な情報を提供します。

  1. テキスト エディターで、次のコードをマニフェスト ファイルに追加します。

    <?xml version="1.0" encoding="utf-8" ?>
    <OfficeApp xmlns="http://schemas.microsoft.com/office/appforoffice/1.1"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:type="TaskPaneApp">
        <Id>[Replace_With_Your_GUID]</Id>
        <Version>1.0</Version>
        <ProviderName>[Provider Name]</ProviderName>
        <DefaultLocale>EN-US</DefaultLocale>
        <DisplayName DefaultValue="Get Doc add-in" />
        <Description DefaultValue="My get PowerPoint or Word document add-in." />
        <IconUrl DefaultValue="http://officeimg.vo.msecnd.net/_layouts/images/general/office_logo.jpg" />
        <SupportUrl DefaultValue="[Insert the URL of a page that provides support information for the app]" />
        <Hosts>
            <Host Name="Document" />
            <Host Name="Presentation" />
        </Hosts>
        <DefaultSettings>
            <SourceLocation DefaultValue="[Network location of app]/GetDoc_App.html" />
        </DefaultSettings>
        <Permissions>ReadWriteDocument</Permissions>
    </OfficeApp>
    
  2. UTF-8 エンコードを使用 してファイルをGetDoc_App.xml としてネットワークの場所またはアドイン カタログに保存します。

アドインのユーザー インターフェイスを作成する

アドインのユーザー インターフェイスでは、 GetDoc_App.html ファイルに直接書き込まれた HTML を使用できます。 アドインのプログラミング ロジックと機能は、JavaScript ファイル (たとえば、 GetDoc_App.js) に含まれている必要があります。

以下の手順を使用して、見出しと 1 つのボタンを含むアドインの簡単なユーザー インターフェイスを作成します。

  1. テキスト エディターの新しいファイルで、選択した Office アプリケーションの HTML を追加します。

    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="UTF-8" />
            <meta http-equiv="X-UA-Compatible" content="IE=Edge"/>
            <title>Publish presentation</title>
            <link rel="stylesheet" type="text/css" href="Program.css" />
            <script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.0.min.js" type="text/javascript"></script>
            <script src="https://appsforoffice.microsoft.com/lib/1/hosted/office.js" type="text/javascript"></script>
            <script src="GetDoc_App.js"></script>
        </head>
        <body>
            <form>
                <h1>Publish presentation</h1>
                <br />
                <div><input id='submit' type="button" value="Submit" /></div>
                <br />
                <div><h2>Status</h2>
                    <div id="status"></div>
                </div>
            </form>
        </body>
    </html>
    
  2. UTF-8 エンコードを使用 してファイルをGetDoc_App.html としてネットワークの場所または Web サーバーに保存します。

    注:

    アドインの ヘッド タグに、Office.js ファイルへの有効なリンクを含む スクリプト タグが含まれていることを確認します。

  3. いくつかの CSS を使用して、アドインにシンプルでモダンでプロフェッショナルな外観を提供します。 次の CSS を使用して、アドインのスタイルを定義します。

    テキスト エディターで、新しいファイルに次の CSS を追加します。

    body
    {
        font-family: "Segoe UI Light","Segoe UI",Tahoma,sans-serif;
    }
    h1,h2
    {
        text-decoration-color:#4ec724;
    }
    input [type="submit"], input[type="button"]
    {
        height:24px;
        padding-left:1em;
        padding-right:1em;
        background-color:white;
        border:1px solid grey;
        border-color: #dedfe0 #b9b9b9 #b9b9b9 #dedfe0;
        cursor:pointer;
    }
    
  4. UTF-8 エンコードを使用 してProgram.css ファイルをネットワークの場所または GetDoc_App.html ファイルが配置されている Web サーバーに保存します。

ドキュメントを取得するための JavaScript を追加する

アドインのコードでは、Office.initialize イベントのハンドラーが、フォーム上の [送信] ボタンのクリック イベントのハンドラーを追加し、アドインの準備ができたことをユーザーに知らせます。

次のコード例は、イベントのイベント ハンドラー Office.initialize と、 updateStatus状態 div に書き込むヘルパー関数 である を示しています。

// The initialize or onReady function is required for all add-ins.
Office.initialize = function (reason) {

    // Checks for the DOM to load using the jQuery ready method.
    $(document).ready(function () {

        // Run sendFile when Submit is clicked.
        $('#submit').on("click", function () {
            sendFile();
        });

        // Update status.
        updateStatus("Ready to send file.");
    });
}

// Create a function for writing to the status div.
function updateStatus(message) {
    var statusInfo = $('#status');
    statusInfo[0].innerHTML += message + "<br/>";
}

UI で [送信] ボタンを選択すると、アドインは、Document.getFileAsync メソッドの呼び出しを含む関数を呼び出sendFileします。 メソッドは getFileAsync 、Office JavaScript API の他のメソッドと同様に非同期パターンを使用します。 これには、1 つの必須パラメーター fileType と、 オプションコールバックという 2 つの省略可能なパラメーターがあります。

fileType パラメーターは、FileType 列挙体 Office.FileType.Compressed ("compressed")、("pdf") Office.FileType.PDF 、または Office.FileType.Text ("text") の 3 つの定数のうちの 1 つを受け取ります。 各プラットフォームの現在のファイルの種類のサポートは、 Document.getFileType 解説の下に一覧表示されます。 fileType パラメーターに Compressed を渡すと、メソッドは現在のgetFileAsyncドキュメントを PowerPoint プレゼンテーション ファイル (*.pptx) またはドキュメント ファイル (*.docx) をWordして、ローカル コンピューター上にファイルの一時コピーを作成して返します。

メソッドは getFileAsyncFile オブジェクトとして ファイルへの参照を返します。 オブジェクトは File 、次の 4 つのメンバーを公開します。

プロパティは size 、ファイル内のバイト数を返します。 は sliceCount 、ファイル内の Slice オブジェクト (この記事で後述) の数を返します。

次のコードを使用して、 メソッドを使用してDocument.getFileAsync現在の PowerPoint または Word ドキュメントをFileオブジェクトとして取得し、ローカルに定義getSliceされた関数を呼び出します。 Fileオブジェクト、カウンター変数、およびファイル内のスライスの合計数は、匿名オブジェクトの の 呼び出しgetSliceで一緒に渡されることに注意してください。

// Get all of the content from a PowerPoint or Word document in 100-KB chunks of text.
function sendFile() {
    Office.context.document.getFileAsync("compressed",
        { sliceSize: 100000 },
        function (result) {

            if (result.status === Office.AsyncResultStatus.Succeeded) {

                // Get the File object from the result.
                var myFile = result.value;
                var state = {
                    file: myFile,
                    counter: 0,
                    sliceCount: myFile.sliceCount
                };

                updateStatus("Getting file of " + myFile.size + " bytes");
                getSlice(state);
            } else {
                updateStatus(result.status);
            }
        });
}

ローカル関数 getSlice は、 メソッドを呼び出して File.getSliceAsync オブジェクトからスライスを File 取得します。 メソッドは getSliceAsync 、スライスの Slice コレクションから オブジェクトを返します。 このメソッドには、 sliceIndexcallback という 2 つの必須パラメーターがあります。 sliceIndex パラメーターは、インデクサーとして整数をスライスのコレクションに取り込みます。 Office JavaScript API の他のメソッドと同様に、メソッドは getSliceAsync コールバック関数をパラメーターとして受け取り、メソッド呼び出しの結果を処理します。

オブジェクトを Slice 使用すると、ファイルに含まれるデータにアクセスできます。 メソッドの options パラメーターに特に指定がない限り、オブジェクトのgetFileAsyncSliceサイズは 4 MB です。 オブジェクトは Sliceサイズデータ、インデックスの 3 つのプロパティを公開 します。 プロパティは size 、スライスのサイズ (バイト単位) を取得します。 プロパティは index 、スライスのコレクション内のスライスの位置を表す整数を取得します。

// Get a slice from the file and then call sendSlice.
function getSlice(state) {
    state.file.getSliceAsync(state.counter, function (result) {
        if (result.status == Office.AsyncResultStatus.Succeeded) {
            updateStatus("Sending piece " + (state.counter + 1) + " of " + state.sliceCount);
            sendSlice(result.value, state);
        } else {
            updateStatus(result.status);
        }
    });
}

プロパティは Slice.data 、ファイルの生データをバイト配列として返します。 データがテキスト形式 (つまり、XML かプレーン テキスト) の場合、スライスには生テキストが含まれています。 の fileType パラメーターDocument.getFileAsync対して Office.FileType.Compressed を渡すと、スライスにはファイルのバイナリ データがバイト配列として含まれます。 In the case of a PowerPoint or Word file, the slices contain byte arrays.

バイト配列のデータを Base64 でエンコードされた文字列に変換するには、独自の関数を実装 (または利用可能なライブラリを使用) する必要があります。 JavaScript での Base64 エンコーティングについては、「 Base64 エンコードとデコード」を参照してください。

データを Base64 に変換したら、HTTP POST 要求の本文など、いくつかの方法でデータを Web サーバーに送信できます。

スライスを Web サービスに送信するために次のコードを追加します。

注:

このコードは、PowerPoint または Word ファイルを複数のスライスで Web サーバーに送信します。 Web サーバーまたはサービスは、個々のスライスを 1 つのファイルに追加し、そのスライスを .pptx または .docx ファイルとして保存してから、操作を実行する必要があります。

function sendSlice(slice, state) {
    var data = slice.data;

    // If the slice contains data, create an HTTP request.
    if (data) {

        // Encode the slice data, a byte array, as a Base64 string.
        // NOTE: The implementation of myEncodeBase64(input) function isn't
        // included with this example. For information about Base64 encoding with
        // JavaScript, see https://developer.mozilla.org/docs/Web/JavaScript/Base64_encoding_and_decoding.
        var fileData = myEncodeBase64(data);

        // Create a new HTTP request. You need to send the request
        // to a webpage that can receive a post.
        var request = new XMLHttpRequest();

        // Create a handler function to update the status
        // when the request has been sent.
        request.onreadystatechange = function () {
            if (request.readyState == 4) {

                updateStatus("Sent " + slice.size + " bytes.");
                state.counter++;

                if (state.counter < state.sliceCount) {
                    getSlice(state);
                } else {
                    closeFile(state);
                }
            }
        }

        request.open("POST", "[Your receiving page or service]");
        request.setRequestHeader("Slice-Number", slice.index);

        // Send the file as the body of an HTTP POST
        // request to the web server.
        request.send(fileData);
    }
}

名前が示すように、 メソッドは File.closeAsync ドキュメントへの接続を閉じ、リソースを解放します。 Office アドインサンドボックスでは、ファイルへのスコープ外の参照がガベージ コレクションされますが、コードが完了したら、ファイルを明示的に閉じるのがベスト プラクティスです。 メソッドには closeAsync 、呼び出しの完了時に呼び出す関数を指定する 1 つのパラメーター コールバックがあります。

function closeFile(state) {
    // Close the file when you're done with it.
    state.file.closeAsync(function (result) {

        // If the result returns as a success, the
        // file has been successfully closed.
        if (result.status === Office.AsyncResultStatus.Succeeded) {
            updateStatus("File closed.");
        } else {
            updateStatus("File couldn't be closed.");
        }
    });
}

最終的な JavaScript ファイルは次のようになります。

/*
 * Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
 * See LICENSE in the project root for license information.
 */

// The initialize or onReady function is required for all add-ins.
Office.initialize = function (reason) {

    // Checks for the DOM to load using the jQuery ready method.
    $(document).ready(function () {

        // Run sendFile when Submit is clicked.
        $('#submit').on("click", function () {
            sendFile();
        });

        // Update status.
        updateStatus("Ready to send file.");
    });
}

// Create a function for writing to the status div.
function updateStatus(message) {
    var statusInfo = $('#status');
    statusInfo[0].innerHTML += message + "<br/>";
}

// Get all of the content from a PowerPoint or Word document in 100-KB chunks of text.
function sendFile() {
    Office.context.document.getFileAsync("compressed",
        { sliceSize: 100000 },
        function (result) {

            if (result.status === Office.AsyncResultStatus.Succeeded) {

                // Get the File object from the result.
                var myFile = result.value;
                var state = {
                    file: myFile,
                    counter: 0,
                    sliceCount: myFile.sliceCount
                };

                updateStatus("Getting file of " + myFile.size + " bytes");
                getSlice(state);
            } else {
                updateStatus(result.status);
            }
        });
}

// Get a slice from the file and then call sendSlice.
function getSlice(state) {
    state.file.getSliceAsync(state.counter, function (result) {
        if (result.status == Office.AsyncResultStatus.Succeeded) {
            updateStatus("Sending piece " + (state.counter + 1) + " of " + state.sliceCount);
            sendSlice(result.value, state);
        } else {
            updateStatus(result.status);
        }
    });
}

function sendSlice(slice, state) {
    var data = slice.data;

    // If the slice contains data, create an HTTP request.
    if (data) {

        // Encode the slice data, a byte array, as a Base64 string.
        // NOTE: The implementation of myEncodeBase64(input) function isn't
        // included with this example. For information about Base64 encoding with
        // JavaScript, see https://developer.mozilla.org/docs/Web/JavaScript/Base64_encoding_and_decoding.
        var fileData = myEncodeBase64(data);

        // Create a new HTTP request. You need to send the request
        // to a webpage that can receive a post.
        var request = new XMLHttpRequest();

        // Create a handler function to update the status
        // when the request has been sent.
        request.onreadystatechange = function () {
            if (request.readyState == 4) {

                updateStatus("Sent " + slice.size + " bytes.");
                state.counter++;

                if (state.counter < state.sliceCount) {
                    getSlice(state);
                } else {
                    closeFile(state);
                }
            }
        }

        request.open("POST", "[Your receiving page or service]");
        request.setRequestHeader("Slice-Number", slice.index);

        // Send the file as the body of an HTTP POST
        // request to the web server.
        request.send(fileData);
    }
}

function closeFile(state) {
    // Close the file when you're done with it.
    state.file.closeAsync(function (result) {

        // If the result returns as a success, the
        // file has been successfully closed.
        if (result.status === Office.AsyncResultStatus.Succeeded) {
            updateStatus("File closed.");
        } else {
            updateStatus("File couldn't be closed.");
        }
    });
}