Search code examples
google-apps-scriptgoogle-docs

Get InlineImage in Specific Tables from Google Document


I encountered the following problem. I have a Google Document, that contains a bunch of table objects and some of those tables contain inline images themselves.

With the Body.getImages() function I should be able to get the images of the whole document (right?). But is there any way to get the images from a specific table or is there a way to determine in which tables the images retrieved by the Body.getImages() method are located?

In case you are wondering what this is used for: My Google Doc is used to store several multiple-choice exam questions, where each question is represented by a table. I am trying to write a script to export these questions to a specific format and I encountered the problem that some of those questions contain images.


Solution

  • Correct - body.getImages() will return an array of images.

    We can use this array of images to find the corresponding table's for each image. If we use a recursive function on each image, we can getParent() up the document tree until the Parent Table to a particular image is found, then we list the element number (the ChildIndex) for the Table. If there is a "Question #" header in the table, we can search for it and return the question number of the located 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));
          
        }
    

    Example Logs

    Example Doc