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

我与影子孤独终老i 提交于 2020-07-08 05:53:10

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/62263386/how-do-i-add-a-bookmark-within-the-body-of-a-word-doc-using-office-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!