-
-
Save atlasloewenherz/aaf08bf7aba478f5efa5 to your computer and use it in GitHub Desktop.
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
// Replace this with ID of your template document. | |
var TEMPLATE_ID = ''; | |
// var TEMPLATE_ID = '1wtGEp27HNEVwImeh2as7bRNw-tO4HkwPGcAsTrSNTPc'; // Demo template | |
// Demo script - http://bit.ly/createPDF | |
/** | |
* 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.getBody(), | |
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, | |
pdfFile; | |
// Replace the keys with the spreadsheet values | |
for (;columnIndex < headerRow[0].length; columnIndex++) { | |
copyBody.replaceText('%' + headerRow[0][columnIndex] + '%', | |
activeRow[0][columnIndex]); | |
} | |
// Create the PDF file and delete the doc copy | |
copyDoc.saveAndClose(); | |
pdfFile = DriveApp.createFile(copyFile.getAs("application/pdf")); | |
copyFile.setTrashed(true); | |
return pdfFile; | |
} // createPdf() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment