Using Google App Scripts for contract assembly and save as PDF documents

I've been building complex document assembly systems since dinosaurs roamed the earth. And by dinosaurs, I mean, 286 computers running Word for DOS 4.0.

This is a simple, but effective, method in Google Apps Script to generate multiple PDF contracts in a matter of seconds.

I provide the code below. In this video, I go through the code line-by-line to explain the logic and features.

VIDEO: CODE WALK THRU

GOOGLE APP SCRIPT CODE EXAMPLE

You will have to replace the template and folder Id's with those from your Google Drive and documents.

function generateContracts() {

  const contractorSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Contractor Agreements");  //enter whatever you name your sheet here.
  const contractData = contractorSheet.getDataRange().getDisplayValues();
  const contractTemplate = DriveApp.getFileById("get-your-document-template-id-from-url");
  const contractFolder = DriveApp.getFolderById("get-your-folder-id-from-url");
  let contractDate = new Date();
  const filePrefix = contractDate.getFullYear() + "-" + String(contractDate.getMonth()).padStart(2,"0") + " - ";
  
  for (let i = 0; i < contractData.length; i++) {
    if (contractData[i][0] == "Y") {
      let myDoc = contractTemplate.makeCopy(filePrefix + contractData[i][1]);
      let newDoc = DocumentApp.openById(myDoc.getId());

      let docBody = newDoc.getBody();
      docBody.replaceText("{{" + contractData[0][1] + "}}", contractData[i][1]);
      docBody.replaceText("{{" + contractData[0][2] + "}}", contractData[i][2]);
      docBody.replaceText("{{" + contractData[0][3] + "}}", contractData[i][3]);
      newDoc.saveAndClose();
      myDoc.moveTo(contractFolder);
      let docPdf = myDoc.getAs('application/pdf');
      contractFolder.createFile(docPdf).setName(filePrefix + contractData[i][1] + ".pdf");
    }

  }

}

 

 

Posted in Automation and tagged .

Leave a Reply

Your email address will not be published. Required fields are marked *