Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add a bookmark within the body of a Word doc using Office JS

The Office JS has provided the following function in preview, but I couldn't find any example.

Here is what I tried but it doesn't seem to work, any idea what I am missing here, since this code inserts the text but the bookmark is not created.

Word.run(function (context)
{
    let range = context.document.getSelection();
    return context.sync().then(function ()
    {
        range.insertText(`Test Bookmark`, Word.InsertLocation.replace);

        let uniqueStr = new Date().getTime();
        let bookmarkName = `Test_BookmarkCode_${uniqueStr}`;
        range.insertBookmark(bookmarkName);
    });
});

Cross posted here.

like image 482
Baig Avatar asked Jun 08 '20 13:06

Baig


People also ask

How do I add multiple bookmarks in Word?

The bookmark name must start with a letter and cannot contain spaces. Use the underscore character to separate words. If you insert multiple bookmarks, enter a descriptive name that is easy to recognize. Select Add to place the bookmark.

What do you use to move from one bookmark to another Word?

On the Bookmark dialog box, select the bookmark name you want to move, or reuse, and click “Add”. The bookmark is moved to the newly selected text or new position in the document. The bookmark name has been reused in a different place in the document. Clicking “Add” to reuse or move a bookmark can be misleading.


Video Answer


1 Answers

So, here is the working code. Apparently, when we insertText, a new range is returned, we need to use that range to insertBookmark.

Word.run(function (context)
{
    let range = context.document.getSelection();
    return context.sync().then(function ()
    {
        let insertedTextRange = range.insertText(`Test Bookmark`, Word.InsertLocation.replace);

        let uniqueStr = new Date().getTime();
        let bookmarkName = `Test_BookmarkCode_${uniqueStr}`;
        insertedTextRange.insertBookmark(bookmarkName);
    });
});
like image 116
Baig Avatar answered Oct 08 '22 18:10

Baig