Google Sheet: Generate a PDF file within a named range and sent it to email

后端 未结 1 1058
挽巷
挽巷 2021-01-25 16:24

I\'m trying to send a PDF file via email. I saw a code here on how to send an email and it kinda works, but it generates all the visible sheets (hidden sheet is not included) in

相关标签:
1条回答
  • 2021-01-25 17:09

    I just added this script / variable to make it work.

    var range = SpreadsheetApp.getActiveSpreadsheet().getRangeByName('print_area_1');

    Here's the full code:

    function sendSheetToPdfwithA1MailAdress(){
      var ss = SpreadsheetApp.getActiveSpreadsheet();
      var sh = ss.getActiveSheet();
      var shName = sh.getName()
      sendSpreadsheetToPdf(0, shName, sh.getRange('Q12').getValue(), sh.getRange('D12').getValue() , "This is it !");
    }
    function sendSpreadsheetToPdf(sheetNumber, pdfName, email,subject, htmlbody, url, sheet, range) {
      var ss = SpreadsheetApp.getActiveSpreadsheet();
      var sheet = ss.getActiveSheet();
      var spreadsheetId = ss.getId()  
      var url_base = ss.getUrl().replace(/edit$/,'');
    
      var rangeParam = ''
      var sheetParam = ''
      if (range) {
        rangeParam = 
          + '&r1=' + (range.getRow() - 1)
          + '&r2=' + range.getLastRow()
          + '&c1=' + (range.getColumn() - 1)
          + '&c2=' + range.getLastColumn()
      }
      if (sheet) {
        sheetParam = '&gid=' + sheet.getSheetId()
      }
     
      var url_ext = 'export?exportFormat=pdf&format=pdf'
          + '&size=folio'
          + '&portrait=true'
          + '&fitw=true'
          + '&top_margin=0.5'              
          + '&bottom_margin=0.5'          
          + '&left_margin=0.5'             
          + '&right_margin=0.5'        
          + '&sheetnames=false&printtitle=false&pagenumbers=false'
          + '&gridlines=true'
          + '&fzr=false'
          + sheetParam
          + rangeParam;
    
      var options = {
        headers: {
          'Authorization': 'Bearer ' +  ScriptApp.getOAuthToken(),
        }
      }
    
      var response = UrlFetchApp.fetch(url_base + url_ext, options);
      var blob = response.getBlob().setName(pdfName + '.pdf');
      if (email) {
        var mailOptions = {
          attachments:blob, htmlBody:htmlbody
        }
    MailApp.sendEmail(
          email, 
          subject+" (" + pdfName +")", 
          "html content only", 
          mailOptions);
      }
    }
    
    0 讨论(0)
提交回复
热议问题