I need to copy the content of a Google Document, and append it to another Document. If I use something like this:
newDoc.getBody().appendParagraph(template.getText());
...I get the text, but lose the formatting that was in my original file. (Bold, Italic, etc.)
How can I copy the contents and formatting to the new document? Is it possible to assign everything to one variable, and copy / paste it to the new document?
Not using only 1 variable , you'll have to iterate all the elements in the doc and copy them one by one.
there are multiple threads on the same subject, try for example this one : How to copy one or more existing pages of a document using google apps script
just read carefully the code and add all the content types that you are supposed to meet in your document (tables, images, pagebreaks...)
EDIT : here is a trial on that idea (to start with)
function copyDoc() {
var sourceDoc = DocumentApp.getActiveDocument().getBody();
var targetDoc = DocumentApp.create('CopyOf'+DocumentApp.getActiveDocument().getName());
// var targetDoc = DocumentApp.openById('another doc ID');
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.TABLE){
body.appendTable(element);
}
else if( type == DocumentApp.ElementType.LIST_ITEM){
body.appendListItem(element);
}
// ...add other conditions (headers, footers...
}
targetDoc.saveAndClose();
}
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