0

Replace Image

by
Published today

Replace an existing image in a Google Doc with one from a public URL.

Script gdocs Verified

The script

Submitted by hugo989 Typescript (fetch-only)
Verified 5 hours ago
1
//native
2

3
/**
4
 * Replace Image
5
 * Replace an existing inline image in a Google Doc with one from a publicly reachable URL, keeping its position. `image_object_id` is a key of the document's `inlineObjects` (Get Document) or the `objectId` returned by Insert Image. Set `tab_id` when the image isn't in the first tab.
6
 */
7
export async function main(
8
  auth: RT.Gdocs,
9
  document_id: string,
10
  image_object_id: string,
11
  image_url: string,
12
  tab_id: string | undefined
13
) {
14
  const response = await fetch(
15
    `https://docs.googleapis.com/v1/documents/${document_id}:batchUpdate`,
16
    {
17
      method: "POST",
18
      headers: {
19
        Authorization: `Bearer ${auth.token}`,
20
        "Content-Type": "application/json",
21
        Accept: "application/json",
22
      },
23
      body: JSON.stringify({ requests: [{
24
          replaceImage: {
25
            imageObjectId: image_object_id,
26
            uri: image_url,
27
            imageReplaceMethod: "CENTER_CROP",
28
            tabId: tab_id || undefined,
29
          },
30
        }] }),
31
    }
32
  )
33
  if (!response.ok) {
34
    throw new Error(`${response.status} ${await response.text()}`)
35
  }
36

37
  return await response.json()
38
}
39