radityaW12
radityaW12

Reputation: 21

Adding images stored in Drive Folder to Google Document via GAS

Is there anyway to insert a number of images stored in a specific drive folder to a specific Google Document using GAS? I have written a function that can only insert a single image. The function looks like the one attached here. While this is working, there are several other images inside the folder that I need to be also included in the document. I have google for some answers and advices, buat most of them works on a single image. The main idea here is to detect the number of images inside the folder and include of those images in the document. Any suggestions?

Many thanks!

function emailresponsepdf(){

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName('Form Responses 1');

  var kolomnamaacara = "3";
  var lastrow = sheet.getLastRow();

  var namaacara = sheet.getRange(lastrow, kolomnamaacara).getValue();

  var folders = DriveApp.getFoldersByName(namaacara);
  while (folders.hasNext()) {
   var folder = folders.next();
  }

  var files = folder.getFiles();
  while (files.hasNext()) {
    var file = files.next().getBlob();
  }

  var copyId = DriveApp.getFileById(docTemplate)
.makeCopy(docName +' untuk '+ namaacara)
.getId();

  var copyDoc = DocumentApp.openById(copyId);

  var copyBody = copyDoc.getActiveSection();

  copyBody.replaceText('keyNamaacara', namaacara);

  copyDoc.getBody().insertImage(0, file);
  copyDoc.saveAndClose();

  var pdf = DriveApp.getFileById(copyId).getAs("application/pdf");

  var subject = "Laporan Acara " + namaacara + "";
  var body = "Ini laporan acara " + namaacara + " yang diadakan oleh " + organisasi + ".";
  var email = "[email protected]";
  MailApp.sendEmail(email, subject, body, {htmlBody: body, attachments: pdf});

  DriveApp.getFileById(copyId).setTrashed(true);
}

Upvotes: 1

Views: 79

Answers (1)

radityaW12
radityaW12

Reputation: 21

Nevermind. I have already got the solution. Should anyone face the same problem,here is the line of codes that I added;

var i = 0;

  var files = folder.getFiles();
  while (files.hasNext()) {
    var file = files.next().getBlob();
    copyDoc.getBody().insertImage([i], file);
    i++;
  }

Which replaces;

var files = folder.getFiles();
  while (files.hasNext()) {
    var file = files.next().getBlob();
  }
.
.
.
.
.
.
copyDoc.getBody().insertImage(0, file);

Hope this helps!

Upvotes: 1

Related Questions