Search code examples
javascriptword-addins

How do I get Microsoft word document text as a string?


I am new to Microsoft Office addins and JS. I am trying to develop a Microsoft Word add-in that converts selected text in the document into QR code. So my problem is getting selected text in the document as simple string. Nothing I tried so far worked. Here is a link for getting the whole text in a document that helped a bit: Word Add-in Get full Document text?. What I need is how to get selected text as a string. I need your help please. I tried the following:

txt = "";
  await Word.run(async (context) => {
    var documentBody = context.document.body;
    context.load(documentBody);
    return context.sync().then(function () {
      console.log(documentBody.text); //full document text
      console.log(document.getSelection.text); //selected only
      txt = documentBody.text.getSelection();
    });
  });


Solution

  • Check the Script Lab. The first sample in Word does exactly what you need:

    $("#run").click(() => tryCatch(run));
    
    function run() {
      return Word.run(function(context) {
        var range = context.document.getSelection();
        range.font.color = "red";
        range.load("text");
    
        return context.sync().then(function() {
          console.log('The selected text was "' + range.text + '".');
        });
      });
    }
    
    /** Default helper for invoking an action and handling errors. */
    function tryCatch(callback) {
      Promise.resolve()
        .then(callback)
        .catch(function(error) {
          // Note: In a production add-in, you'd want to notify the user through your add-in's UI.
          console.error(error);
        });
    }