Replacing Image in Google Doc with Python

33 Views Asked by At

I have a google doc that I am using as a template for creating thousands of automated reports. One part of that is to replace some of the images from the template and replace them with the correct image. I am struggling to get the ID of the image to replace, which doesnt sound like it should be very complicated. According to these docs https://developers.google.com/docs/api/reference/rest/v1/documents/request#replaceimagerequest, The ID of the existing image that will be replaced. The ID can be retrieved from the response of a get request.

But I dont know what request to make. I have tried getting the document like this: document = docs_service.documents().get(documentId=document_id).execute(), but I cannot see anything in there that is obviously an image, except for perhaps the positionedObjectIds field.

Here is the code with the missing field:

requests = [
        {
            "replaceImage": {
                "imageObjectId": ¿where do I get this?,
                "uri": f"https://drive.google.com/file/d/{image_id}/view?usp=drive_link",
                "imageReplaceMethod": "CENTER_CROP",
            }
        }
    ]

Thanks in advance!

1

There are 1 best solutions below

0
sobmortin354 On

In the end I had to:

  1. manually get all image ids from the document document.get("body").get("content", [])
  2. Find all image ids in the format: kix.z9k2rz42vt4f
  3. Then call the command like this, trying each imageObjectId that I found in the first command until it worked:
{
"replaceImage": {
    "imageObjectId": "kix.z9k2rz42vt4f",
    "uri": f"https://drive.google.com/file/d/{new_image}/view?usp=drive_link",
    "imageReplaceMethod": "CENTER_CROP",
  }
}

Of course there may be a better way, but this worked for me. My uri value was also wrong.