Save PDF from URL directly to Drive using Google Apps Script

ADW
2 min readFeb 25, 2021

There is a PDF file on the Internet. Say this one (The Google COVID-19 Community Mobility Report for the US of A).

And you want to save it to your Google Drive.

The tedious way is to download it to your computer. … and then upload it to your Google Drive. (Seems like too much work.)

If only you could send the PDF straight from where it is stored on the Internet, to your Google Drive.

Get the file

Get the URL and set it to a variable:

var url = ‘https://www.gstatic.com/covid19/mobility/2021-02-21_US_Mobility_Report_en.pdf';

Then get the PDF as a blob:

var blob = UrlFetchApp.fetch(url).getBlob();

The UrlFetchApp.fetch(url) method gets the URL and the getBlob() method gets the PDF as a blob.

Save the file

Get the folder ID of the folder you want to save the file to.

The easiest way to do this is to go to the folder and then look at the URL.

The last bit after “/folders/” is the folder ID.

For example, it is “0A5o-TgZZZZZZZYWDog” in https://drive.google.com/drive/u/0/folders/0A5o-TgZZZZZZZYWDog

var foID = ‘0A5o-TgZZZZZZZYWDog’;

Get the folder using the getFolderById(id) method:

var folder = DriveApp.getFolderById(foID);

Save the file to the folder:

folder.createFile(blob);

With the createFile(blob) method, the file name in your Drive will be the name of the original file at the URL you downloaded it from.

If you want to give it a specific name, then you can use the setName(name) method:

folder.createFile(blob).setName('filename.pdf');

Now you might want to make the code more efficient.

So you may try to use either the createFile(name, content) method or the createFile(name, content, mimeType) method.

With these, you don’t need two methods to save and name the file. You can do it in one shot.

But…

Be mindful that in these two methods, the content type is string, not blob. So don’t pass a blob to these methods.

All together now

function savePDFtoDrive() {   // Get the file
var url = 'https://www.gstatic.com/covid19/mobility/2021-02-21_US_Mobility_Report_en.pdf';
var blob = UrlFetchApp.fetch(url).getBlob();
// Save the file
var foID = ‘0A5o-TgZZZZZZZYWDog’;
var folder = DriveApp.getFolderById(foID); folder.createFile(blob).setName('filename.pdf');
}

--

--