Created
June 20, 2024 16:06
-
-
Save danthelion/1d55b71fd8722ff89bc95001eeff82b0 to your computer and use it in GitHub Desktop.
Google Apps Script to download images from a Google Doc into a Google Drive folder
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function saveGoogleDocsImages() { | |
// Define the folder name where the extracted images will be saved | |
const folderName = 'Document Images'; | |
// Check if a folder with the specified name already exists | |
const folders = DriveApp.getFoldersByName(folderName); | |
// If the folder exists, use it; otherwise, create a new folder | |
const folder = folders.hasNext() ? folders.next() : DriveApp.createFolder(folderName); | |
// Get all the images in the document's body and loop through each image | |
DocumentApp.getActiveDocument() | |
.getBody() | |
.getImages() | |
.forEach((image, index) => { | |
// Get the image data as a Blob | |
const blob = image.getBlob(); | |
// Extract the file extension from the Blob's content type (e.g., 'jpeg', 'png') | |
const [, fileExtension] = blob.getContentType().split('/'); | |
// Generate a unique file name for each image based on its position in the document | |
const fileName = `Image #${index + 1}.${fileExtension}`; | |
// Set the Blob's name to the generated file name | |
blob.setName(fileName); | |
// Create a new file in the specified folder with the image data | |
folder.createFile(blob); | |
// Log a message indicating that the image has been saved | |
Logger.log(`Saved ${fileName}`); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment