Baig
Baig

Reputation: 1519

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.

Upvotes: 8

Views: 1489

Answers (2)

Shockwaverider
Shockwaverider

Reputation: 41

(Cannot comment, pls excuse my posting this as an answer.) Two things that got in my way when I implemented something similar to the above solution:

  1. The bookmark name may not be longer than 40 characters.
  2. The name may contain underscores (_), but no dashes (-). Probably most other punctuation characters aren't permitted either.

If you violate either rule you'll get an InvalidArgument exception. I only tried this with the Windows Desktop version of Word 2019, but this behavior is probably the same with other versions.

Upvotes: 0

Baig
Baig

Reputation: 1519

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);
    });
});

Upvotes: 3

Related Questions