Google script replaceAllShapesWithImage with image from drive doesn”t work any more

How about this answer? Please think of this as just one of several possible answers.

Issue and workaround:

I think that the reason of your issue is due to the following modification of official document.

First, we’re making changes to authorization for the Google Drive API. If you authorize download requests to the Drive API using the access token in a query parameter, you will need to migrate your requests to authenticate using an HTTP header instead. Starting January 1, 2020, download calls to files.get, revisions.get and files.export endpoints which authenticate using the access token in the query parameter will no longer be supported, which means you’ll need to update your authentication method.

By above situation, the URL of var imageUrl = file.getDownloadUrl() + "&access_token=" + ScriptApp.getOAuthToken(); cannot be used. For example, when it accesses to the URL, the login screen is displayed even when the access token is used.

In order to avoid this issue, how about the following modification?

Modification points:

  • The file is shared publicly and put to Google Slides. Then, the sharing file is closed.
    • In this case, even when the share of file is closed, the put image on Slides is not removed.
  • The webContentLink is used as the URL.
    • It’s like https://drive.google.com/uc?export=download&id=###.

Modified script:

When your script is modified, it becomes as follows.

function test_image(){
  var imageUrls = DriveApp.getFilesByName("DSC_3632.png");
  var file; // Modified
  while (imageUrls.hasNext()) {
    file = imageUrls.next();
  }
  file.setSharing(DriveApp.Access.ANYONE_WITH_LINK, DriveApp.Permission.VIEW); // Added
  var imageUrl = "https://drive.google.com/uc?export=download&id=" + file.getId(); // Modified
  var model_file = DriveApp.getFileById("your-id");
  var presentation = model_file.makeCopy("totot");
  var presentation =Slides.Presentations.get(presentation.getId())
  var requests = [{
    "replaceAllShapesWithImage": {
      "imageUrl": imageUrl,
      "imageReplaceMethod": "CENTER_INSIDE",
      "containsText": {
        "text": "toto",
        "matchCase": false,
      }
    }
  }];
  var presentationId = presentation.presentationId
  var createSlideResponse = Slides.Presentations.batchUpdate({requests: requests}, presentationId);
  file.setSharing(DriveApp.Access.PRIVATE, DriveApp.Permission.NONE); // Added
}

References:

If I misunderstood your question and this was not the direction you want, I apologize.

Leave a Comment