kjoetools
kjoetools

Reputation: 548

Switching context to new document in Office.js Word Add-in

I have a function that needs to copy the data from an existing document into a new document based on a new template. The problem is that when I want to load the document of the newly created object and insert the data, it instead inserts it into the existing document. It looks like it will not switch context to the new document to work with but I can't find why. Everything works fine without errors, just the data ends up in the wrong document.

This is the code that I'm using:

public convertdoc() {
    this.getText('htmlsource', 'template.txt').subscribe((template) => {
      Word.run(async (context) => {
        const data = context.document.body;
        const xml = data.getOoxml();
        await context.sync();
        const val = xml.value;
        const newDoc = context.application.createDocument(template);
        context.load(newDoc);
        await context.sync();
        newDoc.open();
        await newDoc.context.sync();
        const body = newDoc.context.document.body; 
        await newDoc.context.sync();
        body.insertOoxml(val, 'End');
      }).catch((err) => { this.log('Error: ' + err.message); });
    });
  }

Am I overlooking something or does the newDoc.context not work this way? How can I get to the body of the new document (with the new context)?

Btw, the getText function is a simple ajax function that returns a base64 encoded .dotx file. And the log function just adds the text to an element's innerHtml on the Taskpane.

Upvotes: 0

Views: 498

Answers (2)

kjoetools
kjoetools

Reputation: 548

I ended up writing the ooXML from the current document to localstorage, then opening the new document from the template which has the taskpane set to autoopen. The taskpane then checks if there's something in the localstorage and pastes that into the new document. Works like a charm :)

Upvotes: 2

Wenbo Shi
Wenbo Shi

Reputation: 172

This is not supported, and it's by design behavior. You can only manipulate the content of the current document where the web add-in is inserted. It cannot do cross document operation.

Upvotes: 0

Related Questions