I try to export google doc file as pdf and save it but all file with every encoding is not working.
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);
});
}
please help!!
PS. I try using the API test from here and the first line result shows
%PDF-1.5
%¿÷¢þ
2 0 obj
while mine shows
%PDF-1.5\n%����\n2 0 obj
do I have to encode or decode anything first?
First of all, make sure your packages are up to date & then try :
$ npm uninstall --save google-auth-library
$ npm install --save googleapis@39
Google recommends (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);
});
This is basically a problem with google APIs mismatching versions.
OR
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) => {
If all fails Try using v2
gapi.client.drive.files.export({
fileId: sourceId,
mimeType: "application/pdf"
});