Reputation: 478
I need to highlight words in Word document in my Add-in and when the user needs to remove highlight made by Add-in, it should be possible to remove only the highlights that are made by the Add-in. User made highlights should not be removed.
Right now I can highlight the words with red color in my Add-in and when the user wants to remove highlights, even the user highlights also removed.
Below is my code:
//Add highlights
return context.sync().then(function () {
// Queue a set of commands to change the font for each found item.
for (var i = 0; i < searchResults.items.length; i++) {
searchResults.items[i].font.color = 'red';
searchResults.items[i].font.underline = 'wave';
}
return context.sync();
});
//Remove highlights
Word.run(function (context) {
// Create a proxy object for the document body.
var body = context.document.body;
// Queue a commmand to clear the contents of the body.
body.load("font");
return context.sync().then(function () {
// Queue a set of commands to change the font for each found item.
body.font.color = 'black';
body.font.underline = 'None';
return context.sync();
})
.catch(errorHandler);
});
Upvotes: 1
Views: 547
Reputation: 5036
you have a couple of options for this.
2) is kind of straightforward to implement :)
For 1) please check out the following example, its not doing exactly what you need, but you can get an idea on how to achieve this. The goal is to save each range using the treackedObjects method, that the most important bit. On this case I am creating an array of the ranges that where found, and then you can use it to clean up your highlights. please dont forget to call context.trackedObjects.remove since you are allocating memory to store those objects temporally. By the way in my example make sure to include a combo itesm with id "FoundRanges"
here is a script lab snippet you can use.
function loadCombo() {
Word.run(function (context) {
var rangesAr = [];
var currentlySelectedIndex = 0;
var myRanges = context.document.body.search("Word");
context.load(myRanges, { expand: 'font' });
return context.sync()
.then(function () {
var myCombo = document.getElementById("FoundRanges");
for (var i = 0; i < myRanges.items.length; i++) {
var myItem = document.createElement("option");
myItem.text = myRanges.items[i].text
myCombo.add(myItem);
var newRange = myRanges.items[i].getRange();
rangesAr.push(newRange);
context.trackedObjects.add(newRange);
}
$('#FoundRanges').change(function () {
rangesAr[this.selectedIndex].font.bold = true;
currentlySelectedIndex = this.selectedIndex;
return context.sync()
.catch(function (e) {
console.og(e.message);
})
});
return context.sync()
})
}).catch(function (e) {
console.log(e.message)
})
}
Upvotes: 2