如何使用Drive API获取PDF文件形式的Google Doc,并将其发送给我的API消费者



我使用的是Express、Node和Google Drive API。我正试图用一个PDF文件的斑点来响应对我的端点的API调用。但当我从驱动器API获取文件时,我不想保存文件,我基本上只想将其存储在一个变量中,将其转换为base64并将其发送给我的API消费者。

正在发生的事情的快速概述。我被困在第3-4步。1.消费者使用包含支付信息的有效负载调用我的API端点2.我从模板创建一个新的文档,并使用Docs API使用有效负载填充文档。3.我将文档导出为PDF。4.我向API消费者发送一个响应,其中包含步骤3中的文档。

我该如何做到这一点

我为什么要实现这一点?基本上,我尽量避免创建额外的工作来下载文件并将其存储在某个地方,因为这样我就需要另一个连接。如果我无法避免这种情况,当我想尝试使用Buckets在GCP上处理这种情况时。因此,那里的建议也会有所帮助。

以下是我的代码的概述

// this works
const driveAPI = google.drive({version:"v3", auth: client});
const fileId = await createDocFromTemplate();
const doc = updateDoc( fileId, req.body );
// now it gets tricky
const PDF_FILE = exportDocAsPdf(doc); // how can I temporarily store pdf to a variable?
const PDF_AS_BASE = transformPdfToBase64(PDF_FILE); // how can I convert pdf to base64?
// this is what I want to send back to the API consumer
res.send({
id: fileId,
fileAsPdf : PDF_AS_BASE
})

我相信你的目标如下。

  • 您希望导出Google文档,而不创建文件作为base64数据
  • 您希望使用Node.js中的googleapi来实现这一点
  • 您已经能够使用Drive API导出Google文档

对此,这个答案如何?

很遗憾,我看不到您的updateDoc( fileId, req.body )exportDocAsPdf(doc)transformPdfToBase64(PDF_FILE)的脚本。因此,在这个答案中,我想提出一个示例脚本,用于通过输入Google文档的文件ID来返回PDF格式的base64数据。

示例脚本:

在这种情况下,输入值和输出值分别是Google文档的文件ID和PDF格式的base64数据。

async function exportFile(drive, documentId) {
const res = await drive.files.export(
{
fileId: documentId,
mimeType: "application/pdf",
},
{ responseType: "arraybuffer" }
);
return Buffer.from(res.data).toString("base64");
}
const documentId = "###";  // Please set the Google Document ID
const driveAPI = google.drive({ version: "v3", auth: client });
const base64 = await exportFile(driveAPI, documentId).catch((err) => {
if (err) console.log(err);
});
console.log(base64);
  • 在这种情况下,Google文档将导出为PDF格式。在那个时候,数据就是数组缓冲区。因此,使用Buffer.from(res.data).toString("base64")检索base64数据

参考文献:

  • 谷歌api nodejs客户端
  • 文件:导出

最新更新