Google 驱动器始终通过 API 导出空白 pdf

Google drive always exports blank pdf via 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),但内容为空白:

知道我错过了什么吗?非常感谢!

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

修改后的脚本:

当您的脚本修改时,请修改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

参考文献:

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

@Tanaike 救命恩人,非常感谢!根据您的解决方案,我得出了同样有效的方法:

const writingFile = util.promisify(fs.writeFile);

const pdf = await drive.files.export(
  { fileId: id, mimeType: 'application/pdf' },
  { responseType: 'arraybuffer' }
);
await writingFile('some document.pdf', Buffer.from(pdf.data), 'binary');

对于喜欢异步/等待而不是回调的人。