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.
This sample image was created by k3-studio.
replaceTextToImage(body, replaceText, image, width);
body
: body of document. You can set byDocumentApp.getActiveDocument().getBody()
andDocumentApp.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.
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);
}
- replaceText()
- findText()
- setText()
- insertInlineImage()
- I have proposed this sample script at this thread.
Is it possible to do something similar with Google Slides? I am trying to go through all slides in the deck and replace every instance of "Yes" text with a graphic, but am struggling. I assume you have to change DocumentApp to SlidesApp, and perhaps do something the getBody function which may not work the same way in a Slides presentation (given the separate text boxes, and of course the separate slides with each with its own ID).
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 = "#####Google Slides ID / URL######";
var replaceText = "Yes";
var imageFileId = "#####Image ID / URL#####";
var body = SlidesApp.openById(documentId).getBody();
var image = DriveApp.getFileById(imageFileId).getBlob();
do {
var next = replaceTextToImage(body, replaceText, image, 200);
} while (next);
}