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

Google Apps Script提取PDF第二页功能失效求助

提取PDF第二页的Google Apps Script实现

可以通过Google Apps Script结合Drive API实现提取PDF第二页的需求,以下是修改后的完整代码:

function copySecondPageOfPDFs() {
  const folderId = "MY FOLDER ID"; // 替换为你的目标文件夹ID
  const folder = DriveApp.getFolderById(folderId);
  const files = folder.getFiles();
  const oAuthToken = ScriptApp.getOAuthToken();

  while (files.hasNext()) {
    const file = files.next();
    if (file.getMimeType() === "application/pdf") {
      const fileId = file.getId();
      // 调用Drive API导出PDF的第二页
      const exportUrl = `https://www.googleapis.com/drive/v3/files/${fileId}/export?mimeType=application/pdf&pages=2`;
      const exportParams = {
        method: "get",
        headers: { Authorization: `Bearer ${oAuthToken}` },
        muteHttpExceptions: true
      };
      const exportResponse = UrlFetchApp.fetch(exportUrl, exportParams);
      
      if (exportResponse.getResponseCode() === 200) {
        // 将第二页的Blob保存为新文件
        const secondPageBlob = exportResponse.getBlob().setName(`${file.getName()}_Page_2.pdf`);
        folder.createFile(secondPageBlob);
      } else {
        console.error(`处理文件 ${file.getName()} 失败: ${exportResponse.getContentText()}`);
      }
    }
  }
}

关键说明

  • 指定页码导出:通过Drive API的files/export接口,添加pages=2参数直接导出PDF第二页,无需上传完整文件。
  • 权限处理:使用ScriptApp.getOAuthToken()获取授权令牌,确保脚本有权访问Drive API。
  • 错误排查:开启muteHttpExceptions: true并校验响应码,方便定位处理失败的文件。

注意事项

  1. 需提前启用Drive API:在脚本编辑器中点击「资源」→「高级Google服务」,找到「Drive API」并开启。
  2. 若PDF页数不足2,导出请求会失败,可额外添加页数判断逻辑(比如先获取PDF总页数,再决定是否执行提取)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 06:52:40