I am currently writing a google script, which unfortunately runs too slow. (More than the 6 min limit). The script opens a document, substitutes two strings (which are being set in a google sheet), saves it out as a PDF. Nothing fancy.
I have roughly 200 of these documents to run through this script, but within the 6 minute limit, it only manages to go through six. Is google script just this slow, or have I accidentally made the most inefficient google script ever?
function createAllPDF() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var range = SpreadsheetApp.getActiveSheet().getActiveRange()
var numRows = SpreadsheetApp.getActiveSpreadsheet().getLastRow() - 1;
for(var i = 9; i <= numRows; i++) {
var thisRange = sheet.getRange("A" + n + ":C" + n);
var fond = thisRange.getCell(1, 1).getValue();
var adresse = thisRange.getCell(1, 3).getValue();
thisRange.setBackground('#cfe2f3');
genDoc(fond, adresse);
}
}
//// CREATE PDF ////////////////// FUNCTION FOR GENERATING THE PDF /////////////////////////////////
function genDoc(fond, adresse) {
// Finds the template and duplicate it into a new file.
var template = ("xxxxxxxxxxxx");
var docId = DriveApp.getFileById(template).makeCopy().getId();
// Opens the newly created Document for editing
var doc = DocumentApp.openById(docId);
var body = doc.getActiveSection();
// Renames the newly generated document
var newName = doc.setName(fond);
// Replaces each with the parsed variables.
body.replaceText("%FOND%", fond);
body.replaceText("%ADRESSE%", adresse);
doc.saveAndClose();
//Adds the PDF ID to the invoice_input sheet
var conv = DriveApp.getFileById(docId);
var pdf = conv.getAs("application/pdf");
var fileId = DriveApp.createFile(pdf).getId();
// Gets the PDF file by ID
var thisPDF = DriveApp.getFileById(fileId);
// The ID of the folder I'd like to put the PDF into.
var folderId = "xxxxxxxxxxx";
// Gets the folder by ID
var targetFolder = DriveApp.getFolderById(folderId);
// Adds the PDF to the Folder
targetFolder.addFile(thisPDF);
// Removes the PDF from the root.
var root = DriveApp.getRootFolder().removeFile(thisPDF);
// Deletes the duplicated document
DriveApp.getFileById(docId).setTrashed(true)
return fileId;
}
Any pointers on how to optimize will greatly be appreciated. I am very new to google script and programming in general, so no big words, hehe. Apologize if I am using this board Incorrectly. Please let me know and I will correct.