Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save phillypb/c71fae5bf7d8890b17d7ae82bf84e819 to your computer and use it in GitHub Desktop.
Save phillypb/c71fae5bf7d8890b17d7ae82bf84e819 to your computer and use it in GitHub Desktop.
/**
* Function to replace <<keyword>> tag in Google Doc with relevant image.
*
* @OnlyCurrentDoc
*
* DEVELOPED BY THE GIFT OF SCRIPT: https://www.pbainbridge.co.uk/
*/
function replaceTextToImage() {
// ******************** COMPLETE THESE ITEMS ********************
var searchText = "??";
var imageURL = "??";
var size = 250;
var hyperlinkURL = "??";
// ******************** COMPLETE THESE ITEMS ********************
// get Doc body
var body = DocumentApp.getActiveDocument().getBody();
// get position of text in Doc
var textPosition = body.findText(searchText).getElement();
// replace text with nothing
textPosition.asText().setText("");
// extract ID from URL via regex
var imageFileId = imageURL.match(/[-\w]{25,}/);
// get image blob
var image = DriveApp.getFileById(imageFileId).getBlob();
// insert image and resize
var img = textPosition.getParent().asParagraph().insertInlineImage(0, image);
var w = img.getWidth();
var h = img.getHeight();
img.setWidth(size);
img.setHeight(size * h / w);
// check if a hyperlink has been provided for the image
if (hyperlinkURL == "") {
// do nothing
} else {
// make image clickable
img.setLinkUrl(hyperlinkURL);
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment