Reputation: 23
I'm currently working with Google Apps Script and trying to achieve the following:
I've been able to achieve steps 1 to 3 with the following script I came across:
function menuItem1() {
DocumentApp.getUi() // Or DocumentApp or FormApp.
var sourceDoc = DocumentApp.getActiveDocument().getBody();
var targetDoc = DocumentApp.openById('doc id goes here');
var totalElements = sourceDoc.getNumChildren()
for( var j = 0; j < totalElements; ++j ) {
var body = targetDoc.getBody()
var element = sourceDoc.getChild(j).copy();
var type = element.getType();
if( type == DocumentApp.ElementType.PARAGRAPH ){
body.appendParagraph(element);
}
else if( type == DocumentApp.ElementType.LIST_ITEM){
body.appendListItem(element);
}
}
targetDoc.saveAndClose()
DocumentApp.getUi().alert('New template added');
}
`
However it always pastes the new content at the bottom of the document. I now understand that this is due to the appendParagraph
method and that insertParagraph
is what I should be using. However I'm struggling to understand what index I should be using in order to have my text always paste at the top of the page.
Upvotes: 0
Views: 1049
Reputation: 4048
You can use the insertParagraph
& insertListItem
methods as seen on this tweaked script below.
Tweaks made:
target
docs file.insertParagraph
instead of appendParagraph
.insertListItem
instead of appendListItem
.function menuItem1() {
DocumentApp.getUi() // Or DocumentApp or FormApp.
var sourceDoc = DocumentApp.getActiveDocument().getBody();
var targetDoc = DocumentApp.openById('DOCS ID');
var totalElements = sourceDoc.getNumChildren();
for (var j = (totalElements - 1); j >= 0; j--) { //Reversed the loop to make sure paragraphs/lists are still in order when inserted to the target sheet.
var body = targetDoc.getBody()
var element = sourceDoc.getChild(j).copy();
var type = element.getType();
if (type == DocumentApp.ElementType.PARAGRAPH) {
body.insertParagraph(0, element); //Always insert at the top
}
else if (type == DocumentApp.ElementType.LIST_ITEM) {
body.insertListItem(0, element.copy());; //Always insert at the top
}
}
targetDoc.saveAndClose()
DocumentApp.getUi().alert('New template added');
}
source
docs file.target
docs file.source
docs file gets updated.target
docs file.Upvotes: 0