我正在尝试从谷歌驱动器获取 pdf 并将其下载到浏览器中(我实际上需要它作为数组缓冲区或 blob 以将其与 pspdfkit 一起使用,但这做同样的事情并且更容易描述)。到目前为止,我以多种方式进行了尝试,但无法从我从 api 获得的响应中获得 pdf。
我想说明这是 angular 10 应用程序的一部分,但我认为它不相关。我还需要说明我使用的是 typescript ,但我也做了一个 js 版本来测试,同样的结果似乎是一样的。
doc
对象来自 google drive picker 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
。请帮助:)
最佳答案
我相信你的目标如下。
- 您想使用 Javascript 从 Google 云端硬盘下载 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();
});
引用:
关于javascript - Google Drive Web API 保存和下载 pdf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64739841/