How to copy content and formatting between Google Docs?

后端 未结 1 1917
悲&欢浪女
悲&欢浪女 2020-12-03 13:15

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

相关标签:
1条回答
  • 2020-12-03 13:43

    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();
    }
    
    0 讨论(0)
提交回复
热议问题