从 Google 文档中获取特定表中的 InlineImage

Get InlineImage in Specific Tables from Google Document

我遇到了以下问题。我有一个 Google 文档,其中包含一堆 table 对象,其中一些 table 本身包含内联图像。

使用Body.getImages()函数我应该可以获取整个文档的图像(对吧?)。但是有没有办法从特定的 table 获取图像,或者有没有办法确定 Body.getImages() 方法检索到的图像位于哪个 table 中?

如果您想知道它的用途:我的 Google Doc 用于存储多个选择题,其中每个问题由 table 表示。我正在尝试编写脚本将这些问题导出为特定格式,但我遇到了其中一些问题包含图像的问题。

正确 - body.getImages() 将 return 图像数组。

我们可以使用这个图像数组为每个图像找到对应的 table。如果我们对每个图像使用递归函数,我们可以 getParent() 向上查找文档树,直到 Parent Table 找到特定图像,然后我们列出元素编号( ChildIndex) 对于 Table。如果table中有“题号”header,我们可以搜索return找到Table.

的题号
    function myFunction() {
      var doc = DocumentApp.getActiveDocument();
      var body = doc.getBody();
      var tables = body.getTables();
      var images = doc.getBody().getImages();
      
      Logger.log("Found " + images.length + " images");
      Logger.log("Found " + tables.length + " tables");
      
      //list body element #'s for each tables
      let tableList = []
      tables.forEach(table => tableList.push(String(table.getParent().getChildIndex(table))))
      Logger.log("Tables at body element #s: ", tableList); 
      
      function findQuestionNumber (element, index) {
        parent = element.getParent() 
        //IF found the parent Table
        if (parent.getType() == DocumentApp.ElementType.TABLE) {
          //Find the question # from the Table
          let range = parent.findText("Question")
          //Output where this image was found. (The childindex)
          Logger.log("found Image", String(index + 1), "in ", range.getElement().getParent().getText(), " at body element #", String(parent.getParent().getChildIndex(parent)));
          return
          //use recursion to continue up the tree until the parent Table is found
        } else {
          findQuestionNumber(parent, index)
        }
      }
     
      //Run Function for each image in getImages() Array
      images.forEach((element, index) => findQuestionNumber(element, index));
      
    }