Home > database >  download pdf from URL into gDrive
download pdf from URL into gDrive

Time:11-23

I need to download a PDF from a link in the following format

fileURL = "https://docs.google.com/feeds/download/documents/export/Export?id=<...DOCID...>&revision=3970&exportFormat=pdf"

and add it to gDrive folder.

I have this code, but the generated file just contain "Blob" rather than the actual content

function dFile(fileName,fileURL) {
  var response = UrlFetchApp.fetch(fileURL);
  var fileBlob = response.getBlob().getAs('application/pdf');
  var folder = DriveApp.getFolderById('..folderID..');
  var result = folder.createFile(fileName,fileBlob,MimeType.PDF);
  Logger.log("file created");
}

How to I download the actual PDF?

Update:

I have updated my code and now I get this as generated PDF. Which makes me think I need to auth, but not sure how to do it, I set up all auth in manifest already

function dFile(fileName,fileURL) {
  var response = UrlFetchApp.fetch(fileURL);
  var fileBlob = response.getBlob().getAs('application/pdf');
  var folder = DriveApp.getFolderById('..folderID..');
  var result = folder.createFile(fileBlob).setName(fileName);
  Logger.log("file created");
}

Generated PDF

CodePudding user response:

In your script, how about the following modification?

From:

var response = UrlFetchApp.fetch(fileURL);
var fileBlob = response.getBlob().getAs('application/pdf');

To:

var response = UrlFetchApp.fetch(fileURL, { headers: { authorization: "Bearer "   ScriptApp.getOAuthToken() } });
var fileBlob = response.getBlob();
  • I thought that in your endpoint, getBlob() returns the PDF format.
  • In your script, createFile is used. By this, the required scope has already been included. But, if an error is related to Drive API, please enable Drive API at Advanced Google services.

Note:

  • In your endpoint, if revision=3970 is not existing, an error occurs. Please be careful about this.

Reference:

  • Related