【发布时间】:2020-11-08 15:32:58
【问题描述】:
我正在尝试从谷歌驱动器获取 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。请帮忙:)
【问题讨论】:
-
您在哪里/何时致电
saveFile?因为您需要在驱动器 api 代码中的最终.then回调中调用它,否则resb将为空。 -
我在 resb 填充数据后调用它。我将添加一个示例。
标签: javascript typescript pdf google-drive-api