簡體   English   中英

Google Drive Web API 保存和下載 pdf

[英]Google Drive Web API save and download pdf

我正在嘗試從谷歌驅動器獲取 pdf 並將其下載到瀏覽器中(我實際上需要它作為數組緩沖區或 blob 以將它與 pspdfkit 一起使用,但這與 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); 回復

我相信你的目標如下。

  • 您想使用 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();
 });

參考:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM