2

I have a Google presentation on my Gdrive and I want to export it programatically to PDF. It works fine, but the downloaded file is always blank! Yet with the right number of pages.

Here's my code

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");
  });
});


and here's the generated file with the correct number of slides (2) but blank content:

enter image description here

Any idea what I'm missing? Thanks a lot!

Ben Scarberry
  • 943
  • 2
  • 8
  • 11

2 Answers2

2

From your question, I could understand that you have already been able to export the file from Google Drive with Drive API. So how about this modification?

Modified script:

When your script is modified, please modify exportFile() as follows. Please use responseType as follows.

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);
          }
        });
      }
    }
  );
}

Note:

  • In this case, it supposes that you are using the latest googleapis.

References:

If this was not the direction you want, I apologize.

Tanaike
  • 181,128
  • 11
  • 97
  • 165
0

@Tanaike is a life saver, thank you so much! Based on your solution I came to this which also works:

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');

For people preferring async / await instead of callbacks.

Rasmus Puls
  • 3,009
  • 7
  • 21
  • 58