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
Member of Google Developers Experts Program for Google Workspace (Google Apps Script) and interested in supporting Google Workspace Devs.