首页 > 解决方案 > 从 Word 文档中获取所有书签 ID

问题描述

我想扫描整个文档,其中包含样式为标题 1、标题 2、普通文本和几个项目符号/其他文本(基本上是技术报告)的文本。扫描后,我想提取分配给“标题 2”元素的书签,它们也充当报告中的子标题。

getBookmarks()在 Preview / Beta API 中定义,如果我的光标放在“Heading 2”元素上,它会起作用,如下所示:

async function getBookmarks() {
  Word.run(function(context) {        
    var range = context.document.getSelection();
    var bkmrk = range.getBookmarks(true, true);

    return context.sync().then(function() {
      console.log("The bookmarks read from the document was: " + bkmrk.value);
    });
  }).catch(function(error) {
    console.log("Error: " + JSON.stringify(error));
    if (error instanceof OfficeExtension.Error) {
      console.log("Debug info: " + JSON.stringify(error.debugInfo));
    }
  });
}

从 API 文档的示例代码中可以看出,我已经设法扫描了整个文档并获得了“样式”属性:

async function getParagraphAll() {   await Word.run(async (context) => {
    // Gets the complete sentence (as range) associated with the insertion point.
    let paragraphs = context.document.body.paragraphs
    paragraphs.load("text, style");

    await context.sync();

    // Expands the range to the end of the paragraph to get all the complete sentences.
    let completeParagraph = paragraphs.items[0]
      .getRange()
      .expandTo(
        context.document
          .getSelection()
          .paragraphs.getFirst()
          .getRange("End")
      )

    paragraphs.load("text, style, hyperlink");
    await context.sync();

    for (let i = 0; i < paragraphs.items.length; i++) {
      console.log(paragraphs.items[i].style);
      //let range = paragraphs.items[i].getRange()   - Why is this not working ?
      //let bkmrk = range.getBookmarks(true, false)  - This doesnt get me the bookmark while its in 
      //the loop scanning the entire document. Is it because it fails on "Normal" style? 
      // Should I filter out "Normal" and only run "getBookmarks" on "Heading" style ?
      console.log(paragraphs.items[i].style);
    }   }); }

我在预览 API 链接中提供了对库的引用:https ://appsforoffice.microsoft.com/lib/beta/hosted/office.js

我很难理解为什么我可以在光标级别获取书签但是当我想为整个文档获取它时,它只会显示

在加载任何属性之前执行 context.sync() 。不需要负载。

标签: ms-wordoffice-jsoffice-addinsword-addins

解决方案


推荐阅读