2
votes

I am working on a word web add-in that involves inserting some text (as OOXML) into a word document.

The insert functionality is working fine but I want the inserted text to have the same font size and colour etc as the area the user is currently editing.

I have got this working to some degree by getting the current paragraph at the cursor like so:

Word.run((context) => {
    var pars = context.document.getSelection().paragraphs;
    pars.load();

    return context.sync().then(() => {
            var par = pars.items[0];
            var font = par.font.load();
            var style = par.style;

            // Do stuff with the style & font...
    });
});

However this seems to be unreliable and sometimes doesn't work.

I want to get the style at the current typing location, or somehow read them directly from the values in the ribbon:

enter image description here

Is there a good way to do this? It seems like this would be a pretty common use case in a word add-in.

1

1 Answers

2
votes

The paragraph isn't going to be reliable scope since it could easily contain content using multiple fonts and sizes. You're also retrieving only the 1st paragraph which even more likely to have a different properties (i.e. a title).

To grab the font information for the exact spot you want to insert your OOXML, you want to use document.getSelection() to return a range object. This will let you fetch the current font at the cursor's location:

return Word.run(function (context) {
    var range = context.document.getSelection();
    range.load('font');

    return context.sync()
        .then(function () {
            console.log("Font: " + range.font.name);
            console.log("Size: " + range.font.size);
        });
});

Note that if the user has a selection that contains multiple fonts, this will return a null for font. To get around that you can rescope the range to the start of the section using getRange("start"):

return Word.run(function (context) {
    var range = context.document.getSelection();
    range = range.getRange("start");
    range.load('font');

    return context.sync()
        .then(function () {
            console.log("Font: " + range.font.name);
            console.log("Size: " + range.font.size);
        });
});