Search code examples
office365word-addins

how can i get contents of word page in Office 365 app


I am creating an Office 365 word application, in which I want to get all the contents (text + images) of page. Currently I am using getSelectedDataAsync() function but in this case I need to select all the contents.

Is there any other way to get all contents without selecting it?


Solution

  • Yes. If you were using the Office 2016,Word for iPad, Word for Mac, we can use the code below to get the text of Word document:

     function getDataFromBody() {
        // Run a batch operation against the Word object model.
        Word.run(function (context) {
    
            // Create a proxy object for the document body.
            var body = context.document.body;
    
            body.load("text");
    
            // Synchronize the document state by executing the queued commands,
            // and return a promise to indicate task completion.
            return context.sync().then(function () {              
                console.log("Body txt contents: " + body.text);
            });
        })
        .catch(function (error) {
            console.log("Error: " + JSON.stringify(error));
            if (error instanceof OfficeExtension.Error) {
                console.log("Debug info: " + JSON.stringify(error.debugInfo));
            }
        });
    }
    

    You can refer to the new version of API from here.

    Update

    Get the Html of body content for Word:

       function getDataFromBody() {
        // Run a batch operation against the Word object model.
        Word.run(function (context) {
    
            // Create a proxy object for the document body.
            var body = context.document.body;
    
            // Queue a commmand to get the HTML contents of the body.
            var bodyHTML = body.getHtml();
    
            // Synchronize the document state by executing the queued commands,
            // and return a promise to indicate task completion.
            return context.sync().then(function () {
                console.log("Body HTML contents: " + bodyHTML.value);
            });
        })
        .catch(function (error) {
            console.log("Error: " + JSON.stringify(error));
            if (error instanceof OfficeExtension.Error) {
                console.log("Debug info: " + JSON.stringify(error.debugInfo));
            }
        });
    }