Need help loading a .docx file into current document

1k views Asked by At

I'm writing an add-in where the user will have the option to load different predefined templates.

I have these templates on my pc as docx files.

I know of the method body.insertFileAsBase64, but I cant get it to work!

function insertTemplate01() {
    Word.run(function (context) {

        var body = context.document.body;
        body.clear();
        body.insertText("rapport 1", "Start");


        return context.sync();

    });
}

So instead of inserting just a string, i want to load in a .docx file as a template.

I think i need a baby-step guide of how to do this.

I dont know how to convert my docx files to base64 and then use them to load into the current document.

Thanks a lot!

1

There are 1 answers

2
Juan Balmori On BEST ANSWER

The body.insertFileAsBase64 must work for your purposes. I am assuming that you are having issues with the base64 encoding of the docx files. Check out this "silly stories" example shows how to get the base64 and then insert it into the document, assuming the documents are available in some URL.

https://github.com/OfficeDev/Word-Add-in-SillyStories/blob/master/sample.js

Here is another discussion on how to get the base64 from a binary: Convert binary data to base64 with javascript

for converting a binary stream into a base64 you can do something like this:

  function insertPickedFile() {
        var myFile = document.getElementById("FileToPick"); // assuming there is a <input type="file" id="FileToPick"> element, btw this will be the handler for its change event.. so  you also need to initialize a handler like      $('#FileToPick').change(insertPickedFile);
    
        var reader = new FileReader();
        reader.onload = (function (theFile) {
            return function (e) {
               
                Word.run(function (context) {
                    var startIndex = e.target.result.indexOf("base64,"); // when you use the readAsDataURL method the base64 is included in the result, we just need to get that substring, and then insert it using office.js :)
                    var mybase64 = e.target.result.substr(startIndex + 7, e.target.result.length);
                    context.document.body.insertFileFromBase64(mybase64, "replace");
                    return context.sync()       

                })                               
            };
        })(myFile.files[0]);

        // Read in the image file as a data URL.
        reader.readAsDataURL(myFile.files[0]);
    
}