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:
- searchText - this is the unique string/pattern in the Doc that you want to replace with an image e.g. "<<keyword>>"
- imageURL - this is the direct link to the image in Google Drive that you wish to use in the Doc.
- size - a numerical value representing the number of pixels for the image's width/height.
- 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:
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).
To your knowledge, Could this be done with Google Sheets
ReplyDeleteHi Taylor
DeleteIt'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 ... ?