7

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?

4

1 回答 1

9

不仅使用 1 variable ,您还必须迭代文档中的所有元素并一一复制它们。

关于同一主题有多个主题,例如尝试这个:如何使用谷歌应用脚​​本复制文档的一个或多个现有页面

只需仔细阅读代码并添加您应该在文档中遇到的所有内容类型(表格、图像、分页符......)

编辑:这是一个关于这个想法的试验(开始)

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();
}
于 2013-11-14T20:43:39.373 回答