Save PDF from URL directly to Drive using Google Apps Script

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:

Then get the PDF as a blob:

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

Get the folder using the getFolderById(id) method:

Save the file to the folder:

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:

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

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store