Skip to content

Instantly share code, notes, and snippets.

@andrewroberts
Last active November 1, 2023 16:41
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save andrewroberts/8985d5d0a50c905ed43b639a97c2035f to your computer and use it in GitHub Desktop.
Save andrewroberts/8985d5d0a50c905ed43b639a97c2035f to your computer and use it in GitHub Desktop.
This is a Google Apps Script that creates a PDF file using a Google Doc template and the values in a Google Spreadsheet. It is based on www.andrewroberts.net/2014/10/google-apps-script-create-pdf/ but allows placeholders to be used in the filename.
// dev: andrewroberts.net
// Replace this with ID of your template document.
var TEMPLATE_ID = ''
// var TEMPLATE_ID = '1wtGEp27HNEVwImeh2as7bRNw-tO4HkwPGcAsTrSNTPc' // Demo template
// Demo script - http://bit.ly/createPDF
// You can specify a name for the new PDF file here, or leave empty to use the
// name of the template. Placeholders can also be placed in here.
var PDF_FILE_NAME = ''
/**
* Eventhandler for spreadsheet opening - add a menu.
*/
function onOpen() {
SpreadsheetApp
.getUi()
.createMenu('Create PDF')
.addItem('Create PDF', 'createPdf')
.addToUi()
} // onOpen()
/**
* Take the fields from the active row in the active sheet
* and, using a Google Doc template, create a PDF doc with these
* fields replacing the keys in the template. The keys are identified
* by having a % either side, e.g. %Name%.
*
* @return {Object} the completed PDF file
*/
function createPdf() {
if (TEMPLATE_ID === '') {
SpreadsheetApp.getUi().alert('TEMPLATE_ID needs to be defined in code.gs')
return
}
// Set up the docs and the spreadsheet access
var copyFile = DriveApp.getFileById(TEMPLATE_ID).makeCopy(),
copyId = copyFile.getId(),
copyDoc = DocumentApp.openById(copyId),
copyBody = copyDoc.getActiveSection(),
activeSheet = SpreadsheetApp.getActiveSheet(),
numberOfColumns = activeSheet.getLastColumn(),
activeRowIndex = activeSheet.getActiveRange().getRowIndex(),
activeRow = activeSheet.getRange(activeRowIndex, 1, 1, numberOfColumns).getValues(),
headerRow = activeSheet.getRange(1, 1, 1, numberOfColumns).getValues(),
columnIndex = 0
// Replace the keys with the spreadsheet values
for (;columnIndex < headerRow[0].length; columnIndex++) {
copyBody.replaceText('%' + headerRow[0][columnIndex] + '%',
activeRow[0][columnIndex])
PDF_FILE_NAME.replace('%' + headerRow[0][columnIndex] + '%',
activeRow[0][columnIndex])
}
// Create the PDF file, rename it if required and delete the doc copy
copyDoc.saveAndClose()
var newFile = DriveApp.createFile(copyFile.getAs('application/pdf'))
if (PDF_FILE_NAME !== '') {
newFile.setName(PDF_FILE_NAME)
}
copyFile.setTrashed(true)
SpreadsheetApp.getUi().alert('New PDF file created in the root of your Google Drive')
} // createPdf()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment