Search code examples
jqueryhtmlms-wordoffice-jsword-addins

How to get HTML content of Microsoft Word document?


I have used the below code in order to get the HTML content of Microsoft Word Document:

Word.run(function (context) {
                    var body = context.document.body;
                    context.load(body, 'html');
                    console.log(body.getHtml());

                    return context.sync().then(function () {
                        console.log("Content is fetched:", body.getHtml().value);
                    });
                })
                .catch(function(error){
                    // Log additional information, if applicable:
                    if (error instanceof OfficeExtension.Error) {
                        console.log(error.debugInfo);
                    }
                });

Here in the above code body.getHtml() prints an object which inside of it there is the content I expect. To retrieve that data I use .value to get actual HTML content, but it gives the below error:

There is an error in word data fetch RichApi.Error: "The value of the result object has not been loaded yet. Before reading the value property, call "context.sync()" on the associated request context."

I have issued context.sync(), but the same error appears. Any help here?


Solution

  • The fundamental issue here is that you get the HTML with a method call, you don't load stuff like this, its implicit, but you want to make sure you sync before getting the values :)

    this is how it works check sample below:

    Word.run(function (context) {
            var myHTML  = context.document.body.getHtml();
        
            return context.sync()
                .then(function() {
                    console.log(myHTML.value);
                });
        });