AppsScriptPulse

How to extract images from Google Docs and Google Slides using Google Apps Script

Learn how extract all the embedded images from a Google Document or Google Slides presentation and save them as individual files in a specified folder in your Google Drive.

Often I’ll use Google Docs for drafting blog posts. With the introduction of Duet AI having a generative assistant in situ helps with the creative process. As well as text Google Docs is a really simple canvas for quickly copy/pasting screenshots. Copying content from Google Docs to WYSIWYG editors can sometimes be challenging, particularly, when it comes to images.

Next time I encounter this problem I’ll be using the script solution from Amit Agarwal, which can extract images from Google Docs and Slides and save them to Google Drive. I’m sure there are many other situations where this snippet could come in handy.

Source: How to Extract Images from Google Docs and Google Slides – Digital Inspiration

PDFApp and many recipes for ‘cooking’ PDFs with Google Apps Script

Unfortunately, there are no built-in methods for directly managing PDF data using Google Apps Script. Fortunately, after the V8 runtime has been released, several raw Javascript libraries could be used with Google Apps Script. pdf-lib is also one of them. When this is used, PDF data can be cooked over Google Apps Script. In this report, I would like to introduce achieving this using a Google Apps Script library.

Google Apps Script is a powerful tool for automating tasks. It can be used to process data, create spreadsheets, and send emails. One of the limitations of Apps Script is that it does not have built-in support for PDF files. However, there are a number of third-party libraries that can be used to work with PDF files and in Pulse we’ve featured a number of posts from Kanshi Tanaike where they have explored the pdf-lib is a JavaScript library.

This work has culminated in PDFApp, a dedicated Apps Script library created by Kanshi Tanaike based on the pdf-lib, but optimised for Apps Script. The source post includes a number of recipes for handling PDF files listed below:

  • Export pages from a PDF
  • Get metadata of a PDF
  • Update metadata of a PDF
  • Reorder pages of a PDF
  • Merge PDF files
  • Convert PDF pages to PNG files
  • Get values from PDF form
  • Set values to PDF form
  • Create PDF form using Google Slide as a template
  • Embed objects into a PDF

The source code for PDFApp is also on GitHub if you want to dig further.

Source: Cooking PDF over Google Apps Script

How to programmatically enable push notifications/watches for file changes in Google Drive with Apps Script

Are you looking for a way to receive notifications in real-time when an important spreadsheet in your Google Drive get modified or is accidently deleted by sometimes? Well, Google Drive offers an API to help you set up a watch on any file in your Google Drive be it a document, presentation or even a PDF file. This means that you can receive instant notifications whenever the content or even permissions of that file changes.

This tutorial explains how you can setup watch notifications on any file in your Google Drive with the help of Google Apps Script.

As part of the Google Drive API you can set up watch notifications on any file in your Google Drive. This means you can receive instant notifications whenever the content or permissions of that file changes. This feature can be useful for a number of scenarios, for example,  if you have sensitive Drive files that you want to closely monitor, or a workflow where you’d like to trigger additional events when a file is updated.

This post from Amit Agarwal explains how you can create a push notification for a Google Drive file using Google Apps Script. As noted in the post you can use Google Apps Script to handle the push notification by creating a doPost Web App, however, not all the response data/headers are available using Google Apps Script. There is a related ticket which had some activity earlier in the year and I would encourage you to star the request to get updates and encourage Google to fix – https://issuetracker.google.com/issues/67764685.

Google Workspace Admins looking for domain/user activity on Drive files might want to look at the Reports API activities endpoint, which can be configured to setup similar watch notifications. You can read more in the Reports API: Drive Activity Report overview.

Source: How to Enable Push Notifications for File Changes in Google Drive with Apps Script – Digital Inspiration

Automatically save attachments for a Google Google to Google Drive using Gmail and Google Apps Script

 

Imagine you’re managing a Google Group, where important attachments are regularly sent. Manually saving these attachments to your Google Drive can be time-consuming and prone to errors. Is there a way to automate this process and ensure that you don’t miss any crucial documents?

It’s quite easy to tie yourself in knots when it comes to scheduling tasks in Google Apps Script to handle data created since the last run. This Medium post from Pablo Pallocchi shows a nice way your can structure Gmail searches using the after: operator combined with a ‘last execution date’ stored in Apps Script Properties Service. The result is a nice solution design to backup attachments sent to a Google Group to Google Drive. There’s lots of scope for extending and/or modifying this solution. All the details are in the source post.

Source: Automatically Save Email Attachments to Google Drive Using Google Apps Script

Bulk create Drive folders with subfolders with Google Apps Script

Bulk create Google Drive folders with multiple subfolders. Control the naming of the folders and how many you want.

Use this tool to bulk create folders with subfolders

Use this tool to bulk create folders with subfolders

The following Google Apps Script is designed to bulk create Google Drive folders with multiple subfolders. You control the naming convention of each folder and exactly how many you want.

Features include:

  1. Runtime control – currently set to 5 minutes 30 seconds. Will ignore rows that have a ‘Folder Link’ so you can continue from where you left off and append further folders should you require.
  2. More subfolders – the Google Sheet has columns for 10 subfolders but you can technically add more (columns) and the code will account for this automatically.
  3. Toast popups to inform you of the progress as folders are created.
  4. ‘Log’ sheet and popup error messages if something goes wrong.
  5. Concatenation – create those useful descriptive folder/file names so items are easier to search for in the future. Concatenate will let you combine values that may exist in different columns in another spreadsheet for example, or take those folder names and prepend/append words around them.

Source: The Gift of Script: Bulk create Drive folders with subfolders

List all files and folders in a selected folder’s directory tree in Google Drive using Google Apps Script

A fast approach to get all items in a directory tree in Google Drive with Google Apps Script. Contains video and edge case handling.

This is an excellent detailed step-by-step tutorial from Scott Donald all about how to efficiently list all files and folders in a folder’s directory tree in Google Drive using Google Apps Script. The in parents method is one we’ve covered before in Pulse, but Scott provides a very comprehensive explanation of what’s going on, plus all the code is available if you would like to reuse in your own projects.

Source: List all files and folders in a selected folder’s directory tree in Google Drive: Apps Script – Yagisanatode

Bulk duplicate Google Drive files using Google Apps Script

The following Google Apps Script tool is designed to take a single Google Drive file e.g. a Doc / Sheet / Slide and make duplicates/copies of it with unique file names. The tool will also create a clickable link within the Google Sheet to each new file copy.

Screenshot of the tool for duplicating Drive files

Screenshot of the tool for duplicating Drive files

Source: The Gift of Script: Bulk duplicate Google Drive files

New Google Apps Script library to convert files with the Drive API (including OCRing image file formats)

Apps Script library to convert between file types, including OCR for image to documents, with a huge repertoire of conversion combinations.

The Drive API offers a whole range of conversions between mimeTypes, but it’s a little fiddly to figure out exactly how. This library takes a file and an a desired output format and converts it for you. Sometimes, there’s not a direct route – for example if you need to convert a word file to a pdf, it first needs to get converted to a Google Doc, then to a Pdf. This library automatically works out and actions any intermediate conversions required.

For those who are unfamiliar MIME types (mimeTypes) is a standard way of identifying a file’s content type, such as text, image, or audio. The MIME type for a file is usually used by applications to determine how to open and display the file. Google Drive is able to convert various files, such as a MS Word document to Google Docs.

Sometimes there isn’t a direct route and this clever library from Bruce Mcpherson can help alleviate the pain. The library works by first checking if there is a direct route between the input and output file formats. If there is, it simply converts the file. If there is no direct route, the library will use the Drive API to first convert the file to a format that can be converted to the output format. For example, if you need to convert a Word file to a PDF, the library will first convert the Word file to a Google Doc, and then convert the Google Doc to a PDF.

Knowing what mimeType to use can be a bit of a challenge but you can also use the library to give a list of known types, or if you prefer a more readable list of Google Drive export MIME types.

Source: Convert any file with Apps Script – Desktop Liberation

Generate and send PDFs from Google Sheets with Google Apps Script 

Automatically create PDFs with information from sheets in a Google Sheets spreadsheet. Once the PDFs are generated, you can email them out directly from Sheets. This solution focuses on creating custom invoices, but you can update the template and script to fit your needs.

Today as part of a customer Google Apps Script introduction workshop, we covered a basic invoice / PDF example. By coincidence this month’s Google Workspace Developers Newsletter highlighted a solution spotlight from the Apps Script samples catalogue which does something very similar.

A trick I learned today from our Lead Workspace Trainer, Tim McLardy, was rather than using UrlFetchApp to get a PDF version of the Google Sheet with the export/?format=pdf url, is instead getting the Google Sheet as a blob and creating a pdf with DriveApp.createFile(). As this technique will generate a PDF with pages with all your Sheet tabs the trick is to selectively hide all but the tabs you want in your PDF. In the case of the example linked as the source post you can rewrite the createPDF() function as:

/**
 * Creates a PDF for the customer given sheet.
 * @param {string} ssId - Id of the Google Spreadsheet
 * @param {object} sheet - Sheet to be converted as PDF
 * @param {string} pdfName - File name of the PDF being created
 * @return {file object} PDF file as a blob
 */
function createPDF(ssId, sheet, pdfName) {
  // Based on https://webapps.stackexchange.com/q/162155/30021
  const ss = sheet.getParent();
  const sheets = ss.getSheets();
  // Hides all sheets that are not the main one
  sheets.forEach(s => {
    if (s.getSheetName() !== INVOICE_TEMPLATE_SHEET_NAME) {   
      s.hideSheet()
    }
  });
  
  // make a pdf of the sheet
  const folder = getFolderByName_(OUTPUT_FOLDER_NAME);
  const pdfFile = folder.createFile(ss.getBlob()).setName(pdfName);
  
  // show all the sheets
  sheets.forEach(s => s.showSheet())
  return pdfFile;
}

Source: Generate & send PDFs from Google Sheets  |  Apps Script  |  Google Developers

Automating the creation of multiple folders in Google Drive with Google Apps Script (with a nice Google Sheet processing code pattern)

 

you can use the following Apps Script to create folders in Google Drive for students and share those folders with their email addresses based on data from a Google Sheet

Whilst this post from Amit Agarwal looks at the automatic creation of Google Drive folders, it’s also worth having a look at it at for an Apps Script pattern for iterating over and processing data from Google Sheets. In particular there is a getStudentData()function that turns the 2D array return from .getValues() into an object array which includes a rowIndex. This makes it easy to update your Google Sheet when each row is processed.

Source: Automating the Creation of Multiple Folders in Google Drive – Digital Inspiration