You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何限制OAuth权限至当前表格并实现PDF导出下载?

问题:Google Sheets限制OAuth权限后PDF下载失败

背景与需求

我在Google Sheets中托管了一份PDF模板,希望调用函数时将其下载到本地,同时限制OAuth权限仅对当前表格生效。其余权限为其他功能所需。

当前OAuth配置(appscript.json)

{
  "timeZone": "Europe/London",
  "oauthScopes": [
    "https://www.googleapis.com/auth/spreadsheets.currentonly",
    "https://www.googleapis.com/auth/script.scriptapp",
    "https://www.googleapis.com/auth/script.external_request",
    "https://www.googleapis.com/auth/script.container.ui"
  ],
  "dependencies": {
    "enabledAdvancedServices": []
  },
  "exceptionLogging": "STACKDRIVER",
  "runtimeVersion": "V8"
}

下载PDF的脚本代码

function downloadPDF() {
  var ss = SpreadsheetApp.getActive(),
    id = ss.getId(),
    sht = ss.getSheetByName("PDF TEMPLATE"),
    shtId = sht.getSheetId(),

    url_base = ss.getUrl().replace(/edit$/,'');
    Logger.log(url_base)
    url =
      url_base +
      id +
      '/export' +
      '?format=pdf&gid=' +
      shtId;
      Logger.log(url)

    var val = 'Habits Checklist';
    val += '.pdf';

    var res = UrlFetchApp.fetch(url, {
      headers: { Authorization: 'Bearer ' + ScriptApp.getOAuthToken() },
    });
    SpreadsheetApp.getUi().showModelessDialog(
      HtmlService.createHtmlOutput(
        '<a target ="_blank" download="' +
          val +
          '" href = "data:application/pdf;base64,' +
          Utilities.base64Encode(res.getContent()) +
          '">Click here</a> to download, if download did not start automatically' +
          '<script> \
          var a = document.querySelector("a"); \
          a.addEventListener("click",()=>{setTimeout(google.script.host.close,10)}); \
          a.click(); \
          </script>'
      ).setHeight(50),
      'Downloading PDF..'
    );
    Logger.log('data:application/pdf;base64,' +
          Utilities.base64Encode(res.getContent()))
}

问题现象

  • 授予完整的spreadsheets权限时脚本可正常运行,但该权限要求获取所有表格的编辑权限,不符合需求
  • 使用spreadsheets.currentonly限制权限后,触发404错误:

Exception: Request failed for https://docs.google.com returned code 404. Truncated server response: <meta name="viewport" c... (use muteHttpExceptions option to examine full response)

  • 文件设为公开共享时脚本正常工作,取消共享后失效

求解决办法,实现仅授予当前表格权限的情况下正常下载PDF,无需公开文件。

内容的提问来源于stack exchange,提问作者Elanu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 23:07:06