SAGY
SAGY

Reputation: 67

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

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 ??

Upvotes: 0

Views: 380

Answers (2)

Kishan Vaishnani
Kishan Vaishnani

Reputation: 192

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();
  });
});

Upvotes: 0

Eugene Astafiev
Eugene Astafiev

Reputation: 49397

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); });


    }

Upvotes: 1

Related Questions