Replacing Images on Google Document in Order using Google Apps Script

Gists

This is a sample script for replacing images on Google Document in order using Google Apps Script.

Sample script

This sample script uses Drive API and Docs API. So, please enable Drive API and Docs API at Advanced Google services. Ref

In this sample script, the images on Google Document are replaced with the image files on your Google Drive in order. Each image in Document is replaced in order of file Ids in fileIds.

function myFunction() {
  // Please set the file IDs of the images in your Google Drive.
  const fileIds = ["###", "###", "###", , , ,];

  // Create direct links of the images.
  const urls = fileIds.map((id) =>
    Drive.Files.get(id).thumbnailLink.replace(/\=s.+/, "=s512")
  );

  // Retrieve the original title of images and set the unique image titles using Docs API.
  const doc = DocumentApp.getActiveDocument();
  const images = doc.getBody().getImages();
  const titles = images.reduce((m, e, i) => {
    const org = e.getAltTitle();
    e.setAltTitle(`sample${i}`);
    m.set(`sample${i}`, { title: org, uri: urls[i] });
    return m;
  }, new Map());
  doc.saveAndClose();

  // Create request body of Docs API.
  const { inlineObjects } = Docs.Documents.get(doc.getId(), {
    fields: "inlineObjects",
  });
  const requests = Object.entries(inlineObjects).reduce(
    (
      ar,
      [
        imageObjectId,
        {
          inlineObjectProperties: { embeddedObject },
        },
      ]
    ) => {
      if (
        embeddedObject.hasOwnProperty("imageProperties") &&
        embeddedObject.title
      ) {
        const { uri } = titles.get(embeddedObject.title);
        ar.push({ replaceImage: { imageObjectId, uri } });
      }
      return ar;
    },
    []
  );

  // Request Docs API using the created request body.
  Docs.Documents.batchUpdate({ requests }, doc.getId());

  // Set the original titles to the images.
  const ar = [...titles];
  DocumentApp.getActiveDocument()
    .getBody()
    .getImages()
    .forEach((e, i) => e.setAltTitle(ar[i][1].title));
}
  • When this script is used, the sample situation as shown at the top of this post can be obtained.

Reference

 Share!