从 google 文档 api 中保存 application/pdf 类型的正确方法是什么?

What is the proper way to save application/pdf type from google doc api?

我尝试将 google doc 文件导出为 pdf 并保存,但所有文件的每种编码都无法正常工作。

async function downloadDoc(auth, res, body){

const drive = google.drive({ version: 'v3', auth });
drive.files.export({
    fileId: '1gJd7167Dw5rSJYWdAfkprtCfjIyqIQu4R9eYpIkg7ho',
    mimeType: 'application/pdf'
}, (err, driveResponse) => {
    if (err) return console.log('The API returned an error: ' + err);
    fs.writeFile('./tmp/tempfile1.pdf', driveResponse.data , {encoding:'ascii'}, (err)=>console.log(err));
    fs.writeFile('./tmp/tempfile2.pdf', driveResponse.data , {encoding:'base64'}, (err)=>console.log(err));
    fs.writeFile('./tmp/tempfile3.pdf', driveResponse.data , {encoding:'binary'}, (err)=>console.log(err));
    fs.writeFile('./tmp/tempfile4.pdf', driveResponse.data , {encoding:'hex'}, (err)=>console.log(err));
    fs.writeFile('./tmp/tempfile5.pdf', driveResponse.data , {encoding:'ucs2'}, (err)=>console.log(err));
    fs.writeFile('./tmp/tempfile6.pdf', driveResponse.data , {encoding:'utf-8'}, (err)=>console.log(err));
    fs.writeFile('./tmp/tempfile7.pdf', driveResponse.data , {encoding:'latin1'}, (err)=>console.log(err));
    // (err) => {
    //     if (err) console.log(err);
    //     console.log("save");
    // });
    res.send(driveResponse);
    return (200);
});
}

请帮忙!!

PS。我尝试使用 here 中的 API 测试,第一行结果显示

%PDF-1.5
    %¿÷¢þ
    2 0 obj

而我的显示

 %PDF-1.5\n%����\n2 0 obj

我必须先编码或解码任何东西吗?

首先,确保您的软件包是最新的,然后尝试:

$ npm uninstall --save google-auth-library
$ npm install --save googleapis@39

Google 推荐 (Here) :

'use strict';

const {google} = require('googleapis');
const sampleClient = require('../sampleclient');
const fs = require('fs');
const os = require('os');
const path = require('path');

const drive = google.drive({
  version: 'v3',
  auth: sampleClient.oAuth2Client,
});

async function runSample() {
  // [START main_body]
  const fileId = '1gJd7167Dw5rSJYWdAfkprtCfjIyqIQu4R9eYpIkg7ho';
  const destPath = path.join(os.tmpdir(), 'temp.pdf');
  const dest = fs.createWriteStream(destPath);
  const res = await drive.files.export(
    {fileId, mimeType: 'application/pdf'},
    {responseType: 'stream'}
  );
  await new Promise((resolve, reject) => {
    res.data
      .on('end', () => {
        console.log(`Done downloading document: ${destPath}.`);
        resolve();
      })
      .on('error', err => {
        console.error('Error downloading document.');
        reject(err);
      })
      .pipe(dest);
  });

这基本上是 google API 版本不匹配的问题。

async function downloadDoc(auth, res, body){

const drive = google.drive({ version: 'v3', auth });
const dest = fs.createWriteStream(name + '.pdf');// Added new line
drive.files.export({
    fileId: '1gJd7167Dw5rSJYWdAfkprtCfjIyqIQu4R9eYpIkg7ho',
    mimeType: 'application/pdf'
}, (err, driveResponse) => {

如果全部失败请尝试使用 v2

gapi.client.drive.files.export({
  fileId: sourceId, 
  mimeType: "application/pdf"
});