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

2

8

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.

Alphonse answered 8/6, 2020 at 13:37 Comment(6)
As this is beta preview API, are you referring to the beta CDN?appsforoffice.microsoft.com/lib/beta/hosted/office.jsIdiosyncrasy
@RaymondLu Yes, I am. <script src="appsforoffice.microsoft.com/lib/beta/hosted/office.js" type="text/javascript"></script>Alphonse
I have tried your code, if i remove this line, it will work, can you have a try? range.insertText(Test Bookmark`, Word.InsertLocation.replace);Idiosyncrasy
@RaymondLu Yes, it worked. Is there a way to add new text and set it as bookmark?Alphonse
@RaymondLu I've posted an answer, all I had to do is to use the range returned by range.insertText to insertBookmark.Alphonse
Awesome, this is great!Idiosyncrasy
A
3

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);
    });
});
Alphonse answered 12/6, 2020 at 10:21 Comment(0)
P
0

(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.

Porkpie answered 19/4, 2023 at 19:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.