Replace text placeholder with image using Google Apps Script
07:31 09 Sep 2021

enter image description here

I am trying to place four images into my google document, they should be formatted to the same size and within a square. I am trying to replace text placeholders but I am open to other methods.

The image URLS are located in my google sheet, and I am initialising them as variables.

I am trying to loop through each of the 4 images and replace each corresponding text placeholder with them.

function createDocument() {
  var headers = Sheets.Spreadsheets.Values.get('1Yy70i8aQ3GZEp5FE5mhO458Bmivu01ZeykG0GFZmrVo', 'A4:AL4');
  var tactics = Sheets.Spreadsheets.Values.get('1Yy70i8aQ3GZEp5FE5mhO458Bmivu01ZeykG0GFZmrVo', 'A5:J26');
  var templateId = '1ajVQxJAgGxXF3ivkaWL5WEv2xhiJc9r0YwxLH5Hm17w';
      
  for(var i = 0; i < tactics.values.length; i++){
        
        // see what the sheets API is returning
        Logger.log(tactics);
        
        // initialise variables from the sheet
        var projectID = tactics.values[i][0];
        var projectName = tactics.values[i][1];
      
        // copy our template and capture the ID of the copied document
        var documentId = DriveApp.getFileById(templateId).makeCopy().getId();
        
        // name the copied doc by projectID
        DriveApp.getFileById(documentId).setName(projectID + 'overview');
        
        // update the body of the document
        var body = DocumentApp.openById(documentId).getBody();
        
        // replace template placeholders with sheet variables
        body.replaceText('##ProjectID##', projectID)
        body.replaceText('##ProjectName##', projectName)

        // initialise images from URLs
        var URL1 = tactics.values[i][10];
        var URL2 = tactics.values[i][11];
        var URL3 = tactics.values[i][12];
        var URL4 = tactics.values[i][13];

        var fileID1 = URL1.match(/[\w\_\-]{25,}/).toString();
        var img1   = DriveApp.getFileById(fileID1).getBlob()
        var item1 = body.appendListItem('Item 1');
        // item1.addPositionedImage(img1); add images so that they are formatted as a square as shown below

enter image description here

A github function to do this has been commented - https://gist.github.com/tanaikech/f84831455dea5c394e48caaee0058b26 - how can I implement this for each of the 4 image URLs?

google-apps-script google-sheets google-docs