Last active
March 16, 2019 22:09
-
-
Save theowoo/7579e82552c700a01ca839085e6c30d2 to your computer and use it in GitHub Desktop.
Google Doc add-on to insert a template to the top of the document
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
/* | |
Google Doc add-on to prepend a template to the top of the document. | |
Based on this appending function: https://stackoverflow.com/a/38556448 | |
Support renumbering of ordered (numbered) list. | |
Usage: | |
Replace <GOOGLE DOC TEMPLATE URL> with the URL of the template document. | |
Open the target document, go to Tools > Script editor. | |
Paste this script into Code.gs. | |
Reload the target document, the add-on will be found under Add-ons menu. | |
The first time you use it, a pop-up will appear and request authorisation | |
for the access of external documents. | |
*/ | |
function onOpen(e) { | |
DocumentApp.getUi() | |
.createAddonMenu() | |
.addItem('Insert template', 'insertTemplate') | |
.addToUi(); | |
} | |
function insertTemplate() { | |
var template_url = '<GOOGLE DOC TEMPLATE URL>'; | |
var mainBody = DocumentApp.getActiveDocument().getBody(); | |
var tempBody = DocumentApp.openByUrl(template_url).getBody(); | |
var listID = null; | |
var lastListID = null; | |
var cursor = DocumentApp.getActiveDocument().getCursor().getElement(); | |
var cursorID = cursor.getParent().getChildIndex(cursor); | |
for(var i = 0;i<tempBody.getNumChildren();i++){ | |
var element = tempBody.getChild(i).copy(); | |
var type = element.getType(); | |
if(type == DocumentApp.ElementType.TABLE){ | |
mainBody.insertTable(cursorID+i, element);} | |
else if(type == DocumentApp.ElementType.PARAGRAPH){ | |
mainBody.insertParagraph(cursorID+i, element);} | |
else if(type == DocumentApp.ElementType.LIST_ITEM){ | |
if(listID==null) // First list item | |
listID = mainBody.insertListItem(cursorID+i, 'temp'); | |
lastListID = listID; | |
var glyph = element.getGlyphType(); | |
var item = mainBody.insertListItem(cursorID+i, element).setListId(listID).setGlyphType(glyph); | |
} | |
else if(type == DocumentApp.ElementType.PAGE_BREAK) | |
mainBody.insertPageBreak(cursorID+i, element); | |
} | |
mainBody.removeChild(listID); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment