401未经授权-通过脚本将Google表格导出为PDF时出现权限错误

时间:2019-01-31 17:53:51

标签: javascript pdf google-apps-script google-sheets

我正在尝试编写一个脚本,该脚本将以PDF格式从Google表格下载指定的工作表并通过电子邮件发送。由于401,对PDF的请求失败,但是我不确定如何解决(如果是代码问题或需要在其他地方设置的权限)。这是我的代码:


function download_as_pdf(pdfName) {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = SpreadsheetApp.getActiveSheet();
  var sheetId = sheet.getSheetId(); 
  var url_base = ss.getUrl().replace(/edit$/,'') + "export?";
  var url_ext = 'exportFormat=pdf'   //export as pdf
      + '&format=pdf'     //export as pdf
      + '&size=letter'      // paper size
      + '&portrait=true'    // orientation, false for landscape
      + '&fitw=true'        // fit to width, false for actual size
      + '&sheetnames=false'  //hide optional headers and footers
      + '&printtitle=false'  //hide optional headers and footers
      + '&pagenumbers=false'  //hide page numbers
      + '&gridlines=false'  // hide gridlines
      + '&fzr=false'       // do not repeat row headers (frozen rows) on each page
      + '&gid='  //the sheet's Id

  var token = ScriptApp.getOAuthToken();

  var params = {
    headers: {
      'Authorization': 'Bearer ' + token,
    },
    'muteHttpExceptions' : true
  };

  var response = UrlFetchApp.fetch(url_base + url_ext + sheetId, params)


  // This indicates 401 response
  Logger.log(response.getResponseCode());

  var blob = response.getBlob().getAs('application/pdf').setName(pdfName + ".pdf");

}

0 个答案:

没有答案