首页 > 解决方案 > Google Drive Web API 保存和下载 pdf

问题描述

我正在尝试从谷歌驱动器获取 pdf 并将其下载到浏览器中(我实际上需要它作为数组缓冲区或 blob 以将其与 pspdfkit 一起使用,但这也是相同的,并且更易于描述)。到目前为止,我以多种方式进行了尝试,但无法从我从 api 获得的响应中获得 pdf。

我想指定这是 angular 10 应用程序的一部分,但我认为这无关紧要。另外我需要指定我使用的是打字稿,但我也做了一个 js 版本来测试,同样似乎产生了相同的结果。

doc对象来自谷歌驱动器选择器google.picker.PickerBuilder

这是我用来获取文件内容的代码

gapi.client.drive.files
 .get({
  fileId: doc.id,
  alt: 'media',
  // mimeType: 'application/pdf', // <- with or without
  // responseType: 'arraybuffer', // <- with or without
 })
 .then((res) => {
  // manipulate res.body
  window.resb=res.body;
  // HERE <- I continue to call saveFile and debug the response
 });

这是我用来测试是否可以将响应用作 pdf 文件的函数:

function saveFile(blob, filename) {
  if (window.navigator.msSaveOrOpenBlob) {
    window.navigator.msSaveOrOpenBlob(blob, filename);
  } else {
    const a = document.createElement('a');
    document.body.appendChild(a);
    const url = window.URL.createObjectURL(blob);
    a.href = url;
    a.download = filename;
    a.click();
    setTimeout(() => {
      window.URL.revokeObjectURL(url);
      document.body.removeChild(a);
    }, 0)
  }
}

这是我尝试将字符串解析为数组缓冲区的另一个函数

function str2ab(str) {
  var buf = new ArrayBuffer(str.length*2); // 2 bytes for each char
  var bufView = new Uint16Array(buf);
  for (var i=0, strLen=str.length; i < strLen; i++) {
    bufView[i] = str.charCodeAt(i);
  }
  return buf;
}

这就是我实际调用download函数的方式

saveFile(new Blob([resb],{type: 'application/pdf',}),'a.pdf'); // <- only one that actually produces an openable pdf file, but empty

或者

saveFile(new Blob([str2ab(resb)],{type: 'application/pdf',}),'a.pdf');

或者

saveFile(new Blob(str2ab(resb),{type: 'application/pdf',}),'a.pdf');

...以及其他一些方法。

我的想法很新鲜,我在a (618).pdf。请帮忙 :)

编辑:附加部分console.log(resb); 资源

标签: javascripttypescriptpdfgoogle-drive-api

解决方案


我相信你的目标如下。

  • 您想使用 Javascript 从 Google Drive 下载 PDF 文件。
  • gapi.client可以用于下载文件。

在这种情况下,我想建议修改从二进制数据转换为 blob 的脚本。

修改后的脚本:

一个简单的修改脚本如下。运行此脚本时,会下载一个 PDF 文件并将其作为文件保存到本地 PC。

gapi.client.drive.files
 .get({
  fileId: doc.id,
  alt: 'media',
 })
 .then((res) => {
   const filename = "sample.pdf";
   
   // Convert binary data to blob.
   const data = res.body;
   const len = data.length;
   const ar = new Uint8Array(len);
   for (let i = 0; i < len; i++) {
     ar[i] = data.charCodeAt(i);
   }
   const blob = new Blob([ar], {type: 'application/pdf'});
   
   // Save the file.
   const a = document.createElement('a');
   document.body.appendChild(a);
   const url = window.URL.createObjectURL(blob);
   a.href = url;
   a.download = filename;
   a.click();
 });

参考:


推荐阅读