Last active
August 29, 2015 13:57
-
-
Save wrboyce/9547498 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| // Example usage, attach a similar trigger to your Spreadsheet's onFormSubmit event | |
| function onFormSubmit(e) { | |
| var templateId = 'YOUR-DOCUMENT-ID-HERE', | |
| filenameTemplate = 'MailMerged Documents/<<Date>>/<<Client Name>>', | |
| documentId = mailMerge(templateId, filenameTemplate, e.namedValues); | |
| if (e.namedValues['Email PDF']) | |
| emailPdf(e.namedValues['Username'], documentId); | |
| } | |
| // Meat & Potatoes | |
| function mailMerge(templateId, filenameTemplate, values) { | |
| var id = DocsList.getFileById(templateId).makeCopy('New MailMerge ' + Math.random().toString(36).substr(2, 12)).getId(), | |
| doc = DocumentApp.openById(id), | |
| pathSplitIndex = filenameTemplate.lastIndexOf('/'), | |
| path = null, filename = filenameTemplate; | |
| if (pathSplitIndex > 0) { | |
| path = filenameTemplate.substr(0, pathSplitIndex); | |
| filename = filenameTemplate.substr(pathSplitIndex + 1); | |
| } | |
| for (var key in values) { | |
| var value = values[key][0]; | |
| key = '<<' + key + '>>'; | |
| path = path.replace(key, value); | |
| filename = filename.replace(key, value); | |
| doc.replaceText(key, value); | |
| } | |
| doc.setName(filename).saveAndClose(); | |
| if (path) { | |
| var pathId = DocsList.getFolder(path); | |
| DocsList.getFileById(id).addToFolder(pathId); | |
| } | |
| return doc.getId(); | |
| } | |
| function emailPdf(email, docId, body) { | |
| var doc = DocumentApp.openById(docId), | |
| pdf = doc.getAs('application/pdf'), | |
| subject = doc.getName(); | |
| if (body === undefined) | |
| body = 'PDF Attached: ' + doc.getName(); | |
| MailApp.sendEmail(email, subject, body, {htmlBody: body, attachments: pdf}); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment