Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
    });
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading