2
votes

I am developping a new addin for Word, with Office.js API.

When I apply "Normal" style with the default User Interface in Word by default it keep all other formating styles in the paragraph (bold, italic, character styles...) and as expected it changes only paragraph style to "Normal"

I am trying to emulate the funcionality of appling style "Normal" to a paragraph Programmatically.

I have this piece of code:

function applyStyleParagraph(styleName) {
    Word.run(function(context) {
        var pars = context.document.getSelection().paragraphs;
        context.load(pars, 'style');
        return context.sync().then(function () {
            for (var i = 0; i < pars.items.length; i++) {
                pars.items[i].style = styleName;
            }
            return context.sync().then(function () {
                console.log('Style: ' + styleName + ' / Style paragraph created');
            });
        })
    }).catch(function(error) {
        console.log(error);
        if (error instanceof OfficeExtension.Error) {
            console.log('Style: ' + styleName  + 
                    ' / Debug info: ' + JSON.stringify(error.debugInfo));
        }
    });
}

The result is that all other formatting styles (bold, italic, strike, character styles) are removed.

¿How can I preserve all other formatting styles?

This issue affects to Word online an Word 2016.

1
I can reproduce this. You may have to record the character styles of all child ranges in the paragraphs in local variables and then reapply them to the child ranges after the paragraph style is changed. I will research this with the product team before making that an answer.Rick Kirkham
Thanks @rick-kirkham. I tried to do so. But performance was quite bad. Upto 10 seconds. You can check code hereDavid Sanz

1 Answers

0
votes

It might be useful to you know that Word's normal behaviour is what is happening - you apply a paragraph style to a paragraph and it will remove, what we call, all manual formatting - that's formatting applied via the font buttons etc on the Home tab, like Bold, Italics, changing color, font name + size etc

Rick Kirkham hit the money shot when he advised that you would need to create and apply character styles (for characters not paragraphs) - ie a built in character style for bold is Strong, for italics is Emphasis, and I create custom character styles for emphasising text in brand colours.

I found this post because I am a VB/VBA developer attempting to convert my macros to Office.js and struggling to understand how to apply a character style to a selected set of characters - I seem to only be able to apply the style to paragraphs - my code ignores the selected word. Grrr. Will post this as a separate question if I can't find an answer.