javascript - Google Drive 始终通过 API 导出空白 pdf

标签 javascript google-drive-api google-slides-api

我的 Gdrive 上有一个 Google 演示文稿,我想以编程方式将其导出为 PDF。它工作正常,但下载的文件总是空白!但页数正确。

这是我的代码

function exportFile(auth, id) {
  const drive = google.drive({
    version: "v3",
    auth: auth
  });
  drive.files.export(
    {
      fileId: id,
      mimeType: "application/pdf"
    },
    (err, res) => {
      if (err) {
        console.log(err);
      } else {
        fs.writeFile("local.pdf", res.data, function(err) {
          if (err) {
            return console.log(err);
          }
        });
      }
    }
  );
}

fs.readFile("credentials.json", (err, content) => {
  if (err) return console.log("Error loading client secret file:", err);
  // Authorize a client with credentials, then call the Google drive API.
  authorize(JSON.parse(content), auth => {
    exportFile(auth, "1mtxWDrPCt8EL_UoSUbrLv38Cu8_8LUm0onSv0MPCIbk");
  });
});


这是生成的文件,其中包含正确数量的幻灯片 (2) 但内容为空白:

enter image description here

知道我错过了什么吗?多谢!

最佳答案

从您的问题中,我了解到您已经能够使用 Drive API 从 Google Drive 导出文件。那么这个修改怎么样?

修改后的脚本:

当您的脚本被修改时,请按如下方式修改exportFile()。请按如下方式使用 responseType

function exportFile(auth, id) {
  const drive = google.drive({
    version: "v3",
    auth: auth
  });
  drive.files.export(
    {
      fileId: id,
      mimeType: "application/pdf"
    },
    { responseType: "arraybuffer" },  // Added
    (err, res) => {
      if (err) {
        console.log(err);
      } else {
        fs.writeFile("local.pdf", Buffer.from(res.data), function(err) { // Modified
          if (err) {
            return console.log(err);
          }
        });
      }
    }
  );
}

注意:

  • 在本例中,假设您使用的是最新的 googleapis .

引用文献:

如果这不是您想要的方向,我深表歉意。

关于javascript - Google Drive 始终通过 API 导出空白 pdf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59921316/

相关文章:

javascript - Angular 4 单元测试出现错误 - 失败 : Cannot read property 'map' of undefined

javascript - 将数组传递给 Javascript Date 构造函数,这是标准的吗?

javascript - Grails-如何通过onchange事件在gsp文件中调用js文件中的函数?

javascript - 如何更改谷歌幻灯片中链接对象指向的工作表?

google-apps-script - 为 DuplicateObject 请求创建带有可变键的 objectIds 映射

javascript - 如果用户使用编辑器本身添加新类别,是否有办法刷新自定义组件中使用的类别列表?

javascript - 将 .ogg blob 转换为 Google Drive 文件

javascript - Google 保存到驱动器按钮在鼠标悬停时隐藏

python - (Python) 如何自动移动创建的文件?

google-slides - 如何在谷歌幻灯片 API 中将幻灯片导出为 HTML/PDF/DOC