Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Replacing Text to Image for Google Document using Google Apps Script

Replacing Text to Image for Google Document using Google Apps Script

This is a sample script for replacing text to image for Google Document using Google Apps Script (GAS). There is a method for replacing text to text at Class Text of DocumentApp. But there are not methods for replacing text to image. So I created this sample script.

Demo :

This sample image was created by k3-studio.

Usage :

replaceTextToImage(body, replaceText, image, width);
  • body : body of document. You can set by DocumentApp.getActiveDocument().getBody() and DocumentApp.openById(documentId).getBody().
  • replaceText : string you want to replace.
  • image : blob of image you want to replace.
  • width : Width of replaced image. The aspect ratio is constant. The unit is pixels. If you don't use this, the original size is used.

Script :

In this sample script, all strings of "sample" in the document are replaced to image with the file ID of imageFileId.

function myFunction() {
  var replaceTextToImage = function(body, searchText, image, width) {
    var next = body.findText(searchText);
    if (!next) return;
    var r = next.getElement();
    r.asText().setText("");
    var img = r.getParent().asParagraph().insertInlineImage(0, image);
    if (width && typeof width == "number") {
      var w = img.getWidth();
      var h = img.getHeight();
      img.setWidth(width);
      img.setHeight(width * h / w);
    }
    return next;
  };

  var documentId = "### Document ID ###";
  var replaceText = "sample";
  var imageFileId = "### File ID of image ###";
  var body = DocumentApp.openById(documentId).getBody();
  var image = DriveApp.getFileById(imageFileId).getBlob();
  do {
    var next = replaceTextToImage(body, replaceText, image, 200);
  } while (next);
}

References :

@deniscanevaro

This comment has been minimized.

Copy link

deniscanevaro commented Nov 27, 2018

bien funciona perfecto

@urwa

This comment has been minimized.

Copy link

urwa commented Feb 14, 2019

eternally grateful for this beauty of a function.

@paulomoisessilva

This comment has been minimized.

Copy link

paulomoisessilva commented Mar 14, 2019

thankssss <3

@ThommenUlgar

This comment has been minimized.

Copy link

ThommenUlgar commented Sep 26, 2019

Great ! Is there a way to :

  • auto-replace the Document ID by the ID of the current document
  • replaceText should be the url of the image source
    ?
    Thank you in advance if you have any idea :-)
@iamhealey

This comment has been minimized.

Copy link

iamhealey commented Dec 21, 2019

This continues to be incredibly useful. Well done!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.