Search code examples
javascriptgoogle-drive-apigoogle-slides-api

Google drive always exports blank pdf via API


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!


Solution

  • 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.