I want to write a Google Docs script that copies a template (which just contains a container bound script) and appends the contents of another document chosen by the user. How would I accomplish this? I already have a way to select the file (the template has a static id), but figure out a way to copy all the content of the document (including inlineImages and hyperLinks) to the my new document.
I guess the only way is to copy elements one by one... there are a whole bunch of document elements but it shouldn't be too hard to be quite exhaustive. Here is how it goes for the most common types, you'll have to add the other ones.
(original code borrowed from an answer by Henrique Abreu)
function importInDoc() {
var docID = 'id of the template copy';
var baseDoc = DocumentApp.openById(docID);
var body = baseDoc.getBody();
var otherBody = DocumentApp.openById('id of source document').getBody();
var totalElements = otherBody.getNumChildren();
for( var j = 0; j < totalElements; ++j ) {
var element = otherBody.getChild(j).copy();
var type = element.getType();
if( type == DocumentApp.ElementType.PARAGRAPH )
body.appendParagraph(element);
else if( type == DocumentApp.ElementType.TABLE )
body.appendTable(element);
else if( type == DocumentApp.ElementType.LIST_ITEM )
body.appendListItem(element);
else if( type == DocumentApp.ElementType.INLINE_IMAGE )
body.appendImage(element);
// add other element types as you want
else
throw new Error("According to the doc this type couldn't appear in the body: "+type);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With