Search code examples
google-apps-scriptgoogle-sheetsautomationspreadsheet

How to generate PDF from a Google Sheet and send copies to specific email accounts when a specific cell in the sheet is edited?


I am trying to make an invoice for a project. The way it works is a person would fill in the required details and as soon as the details are filled. They would edit a specific cell (could be a drop-down like "invoice filled" and "invoice incomplete"). As soon as they click on filled, it would send the sheet as a PDF file to different emails.

I'm having a hard time going around this through apps scripts.


Solution

  • Here is a sample

    function createAndSendPDF() {
      const docID = '___________'; // ID of spreadsheet
      const feuilleID = '0'; // sheetID
      const email = 'emailAddress@email.com';
      // const dossier = DriveApp.getFolderById('____________'); // ID of Folder if you want to save a copy of the pdf file
      const d = Utilities.formatDate(new Date(), "GMT+1", "yyyyMMdd")
      const fichier = 'myFileName' + "_" + d + ".pdf"
      const objet = 'Test pdf';
      const corps = "Please find ...";
    
      const url = 'https://docs.google.com/spreadsheets/d/' + docID + '/export?';
      const exportOptions =
        'exportFormat=pdf&format=pdf' + 
        '&size=A4' + 
        '&portrait=true' +
        '&fitw=true' +
        '&sheetnames=false&printtitle=false' +
        '&pagenumbers=false&gridlines=false' +
        '&fzr=false' +
        '&gid=' + feuilleID;
      var params = {method:"GET",headers:{"authorization":"Bearer "+ ScriptApp.getOAuthToken()}};
      var reponse = UrlFetchApp.fetch(url + exportOptions, params).getBlob();
    
        GmailApp.sendEmail(email, objet, corps, {
          htmlBody: corps,
          attachments: [{
                fileName: fichier,
                content: reponse.getBytes(),
                mimeType: "application/pdf"
            }]
        });
    
      // dossier.createFile(reponse.setName(fichier));
    }