Tuesday, 13 February 2024

Replace text in a Google Doc with an image

The following Google Apps Script is designed to search the body of a Google Doc for a specific string/pattern (i.e. a keyword) and insert an image in place of it, optionally making it a clickable hyperlink too.


Instructions

In this example the code is designed to sit behind the Google Doc so it is bound to it. There are 4 pieces of information to complete in order to setup the script:

  1. searchText - this is the unique string/pattern in the Doc that you want to replace with an image e.g. "<<keyword>>"

  2. imageURL - this is the direct link to the image in Google Drive that you wish to use in the Doc.

  3. size - a numerical value representing the number of pixels for the image's width/height.

  4. hyperlinkURL - if you want the image to be clickable then provide a link for it.


The Code

There are a few bits of code to tease out and explore, but you will find this previous post on replacing text in a Google Doc with a hyperlink covers a good chunk of it. In this instance we do not want to replace our searchText with anything however:

textPosition.asText().setText("");

We can use a regular expression (Regex) to extract our image ID from the imageURL and then get this as a blob:

var imageFileId = imageURL.match(/[-\w]{25,}/);
var image = DriveApp.getFileById(imageFileId).getBlob();

Now we want to insert the image right where our searchText was:

var img = textPosition.getParent().asParagraph().insertInlineImage(0, image);

Then adjust its width/height:

var w = img.getWidth();
var h = img.getHeight();
img.setWidth(size);
img.setHeight(size * h / w);

Our final optional step is to make the image clickable if we provided a hyperlink:

if (hyperlinkURL == "") {
    // do nothing
} else {
   img.setLinkUrl(hyperlinkURL);
};



Download

Replace text in a Google Doc with an image download (please use 'File' > 'Make a copy' for your own version).


2 comments:

  1. To your knowledge, Could this be done with Google Sheets

    ReplyDelete
    Replies
    1. Hi Taylor

      It's not something I've done. There is the ability to insert an image into a cell in a Google Sheet (https://developers.google.com/apps-script/reference/spreadsheet/cell-image). Are you suggesting you want to perform some kind of image search in a spreadsheet and then make some changes ... ?

      Delete