[英]Google drive always exports blank pdf via API
我的 Gdrive 上有一個 Google 演示文稿,我想以編程方式將其導出為 PDF。 它工作正常,但下載的文件總是空白! 然而,頁數正確。
這是我的代碼
function exportFile(auth, id) {
const drive = google.drive({
version: "v3",
auth: auth
});
drive.files.export(
{
fileId: id,
mimeType: "application/pdf"
},
(err, res) => {
if (err) {
console.log(err);
} else {
fs.writeFile("local.pdf", res.data, function(err) {
if (err) {
return console.log(err);
}
});
}
}
);
}
fs.readFile("credentials.json", (err, content) => {
if (err) return console.log("Error loading client secret file:", err);
// Authorize a client with credentials, then call the Google drive API.
authorize(JSON.parse(content), auth => {
exportFile(auth, "1mtxWDrPCt8EL_UoSUbrLv38Cu8_8LUm0onSv0MPCIbk");
});
});
這是生成的文件,其中包含正確數量的幻燈片 (2) 但內容為空白:
知道我錯過了什么嗎? 非常感謝!
從您的問題中,我了解到您已經能夠使用 Drive API 從 Google Drive 導出文件。 那么這個修改怎么樣呢?
當您的腳本被修改時,請按如下方式修改exportFile()
。 請使用responseType
如下。
function exportFile(auth, id) {
const drive = google.drive({
version: "v3",
auth: auth
});
drive.files.export(
{
fileId: id,
mimeType: "application/pdf"
},
{ responseType: "arraybuffer" }, // Added
(err, res) => {
if (err) {
console.log(err);
} else {
fs.writeFile("local.pdf", Buffer.from(res.data), function(err) { // Modified
if (err) {
return console.log(err);
}
});
}
}
);
}
如果這不是您想要的方向,我深表歉意。
@Tanaike 是一個救星,非常感謝! 根據您的解決方案,我得出了同樣有效的解決方案:
const writingFile = util.promisify(fs.writeFile);
const pdf = await drive.files.export(
{ fileId: id, mimeType: 'application/pdf' },
{ responseType: 'arraybuffer' }
);
await writingFile('some document.pdf', Buffer.from(pdf.data), 'binary');
對於更喜歡異步/等待而不是回調的人。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.