'Copy Image Google Apps Script

I built a script that copies the contents of document A and pastes it into a new document, document X. Document B,C,D etc are also copied into document X. All the contents copy over great and everything works wonderfully. However, I recently added an image to document A that isn't copying over correctly. The image does show up in the new document (document x), but instead of showing the actual image it just shows a gray box with a caution triangle in it. I've attached a screenshot of the before and after.

Any tips for getting the image to copy over correctly?

Here's the code:

//Now let's use an array to create a list of optional documents we want to assemble.
  // We know the cover page is always first so let's add it as the first element of the array. 
  var listofDocs = new Array(newDoc.getId())

...

//log the array which you've built
console.log("List of docs are: "+listofDocs)

// Now take the array of documents we created, and add their elements to the newDoc one element at a time and one doc at a time. 
  // Open up the coverpage and tell the system to look at the body of the doc
    var basedoc = DocumentApp.openById(listofDocs[0])
    var body = basedoc.getBody()
  //Open the specified document from listofDocs (one at a time),append each element onto the newDoc one at a time. 
    for (var i = 1; i < listofDocs.length; ++i){
      console.log("looking for elements in: "+ DriveApp.getFileById(listofDocs[i]))
      var otherBody = DocumentApp.openById(listofDocs[i]).getBody()
      var totalElements = otherBody.getNumChildren()
      for (var j=0; j < totalElements; ++j){
        var element = otherBody.getChild(j).copy()
        var type = element.getType()
        console.log("Found an element. Type: "+ type +" in doc: "+ listofDocs[i])
        if (type == DocumentApp.ElementType.PARAGRAPH) body.appendParagraph(element)
        else if (type== DocumentApp.ElementType.TABLE) body.appendTable(element)
        else if (type == DocumentApp.ElementType.LIST_ITEM) body.appendListItem(element)
  • The image was originally a "wrapped" image. I changed it to "inline" thinking that may help, but no luck.
  • I tried adding the following code, but this had no effect. else if (type == DocumentApp.ElementType.INLINE_IMAGE) body.appendImage(element)


Solution 1:[1]

This how I append an image to a report

    var imageFileName='GTCImg'+ selObj.pid;
    var imagesFolder=DriveApp.getFolderById(getGlobal('ImagesDirectoryId'))
    var images=imagesFolder.getFilesByName(imageFileName);
    while(images.hasNext()){
      var imgFile=images.next();
    }
    if(imgFile){
      body.appendImage(Utilities.newBlob(Utilities.base64Decode(imgFile.getBlob().getDataAsString().split(',')[1])));
    }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Cooper