google-apps-scriptgoogle-docs-api

How do I replace an image with Docs API in Google Apps Script?


Seems like all the documentation I can find for using the Docs API with Apps Script is deprecated. I've tried many variations on the below code, but I keep getting a 404 error from the last line. I can print the properties of the doc object and find the current image, so it's really just the update request that seems to be the problem.

function copyDoc() {
  request = {
    name: "Copy of Template",
  };
  doc = Drive.Files.copy(resource= request, fileId= '1AgUGJ5a0_O4U9Jnu9QWG5MX4BGwfmiZvv437xC1bZms');

  doc = Docs.Documents.get(doc.id, {'includeTabsContent': true});
  
  obj = doc.tabs[0].documentTab.inlineObjects
  obj_id = Object.entries(obj)[0][0]

  request = {
    "requests": [
      {
        "replaceImage": {
          "imageObjectId": obj_id,
          "uri": "https://dummyimage.com/300x200/000/fff",
          "imageReplaceMethod": 'CENTER_CROP',
        }
      }
    ],
  }

  Docs.Documents.batchUpdate(resource=request, documentId= doc.id)
}

Solution

  • In your showing script, I think that doc.id is required to be modified to doc.documentId. So, please modify as follows.

    From:

    Docs.Documents.batchUpdate(resource=request, documentId= doc.id)
    

    To:

    Docs.Documents.batchUpdate(resource = request, documentId = doc.documentId);
    

    Also, I think that your showing script can be modified as follows.

    function copyDoc() {
      const fileId = "###"; // Please set your original Google Document ID.
    
      const request1 = { name: "Copy of Template" };
      const copiedFile = Drive.Files.copy(request1, fileId);
      const docId = copiedFile.id;
      const doc = Docs.Documents.get(docId, { 'includeTabsContent': true });
      const obj = doc.tabs[0].documentTab.inlineObjects;
      const obj_id = Object.entries(obj)[0][0];
      const request2 = {
        "requests": [
          {
            "replaceImage": {
              "imageObjectId": obj_id,
              "uri": "https://dummyimage.com/300x200/000/fff",
              "imageReplaceMethod": 'CENTER_CROP',
            }
          }
        ]
      };
      Docs.Documents.batchUpdate(request2, docId);
    }
    

    Reference: