How to copy content and formatting between Google Docs?

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();
}

Leave a Comment