How to insert text inside word doc using word plugin/add-in

103 Views Asked by At

I have developed a word add-in/plugin using yeoman. Now I got stuck where i am calling rest API from word add-in and i am getting content in form of key value pair in dictionary from Rest API call and need to insert that text on word doc under same heading as key in response.

Is it feasible to do ? or we can get word doc from API and we can show this api object(word doc) on same window/word screen using word add-in/plug-in ??

2

There are 2 best solutions below

0
Eugene Astafiev On

You can get the base64 file and then use the following code:

function onaddOpenDoc() {
        Word.run(function (context) {
          
          // this getDocumentAsBase64 assumes a valid base64-encoded docx file
            var myNewDoc = context.application.createDocument(getDocumentAsBase64());
            context.load(myNewDoc);

            return context.sync()
                .then(function () {
                    myNewDoc.open();
                    context.sync();
                }).catch(function (myError) {
                    //otherwise we handle the exception here!
                    showNotification("Error", myError.message);
                })

        }).catch(function (myError) { showNotification("Error", myError.message); });


    }
0
Kishan Vaishnani On

You can try this below solution

Word.run(async (context: any) => {
  const docBody = context.document.body;
  context.load(docBody, "text");
  await context.sync();

  const newDoc = context.application.createDocument();
  context.load(newDoc);

  return context.sync().then(async () => {
    newDoc.body.insertText(docBody.text, Word.InsertLocation.start);
    await context.sync();

    const paragraphs = newDoc.body.paragraphs;
    context.load(paragraphs, "items");
    await context.sync();

    for (let i = 0; i < paragraphs.items.length; i++) {
      const para = paragraphs.items[i].text.trim();

      if (para != "APIkey") {
        // <------ check with your KEY
        const para = paragraphs.items[i]
          .getRange()
          .insertText("APIsKeyResponse", Word.InsertLocation.replace); // <------ replace with your value
        await context.sync();
      }
    }
    newDoc.open();
    return context.sync();
  });
});