如何在 Google Docs 之间复制内容和格式?

cra*_*ice 5 google-docs google-apps-script

我需要复制 Google 文档的内容,并将其附加到另一个文档。如果我使用这样的东西:

newDoc.getBody().appendParagraph(template.getText());

...我得到了文本,但丢失了原始文件中的格式。(粗体斜体等)

如何将内容和格式复制到新文档?是否可以将所有内容分配给一个变量,然后将其复制/粘贴到新文档中?

Ser*_*sas 6

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

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

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

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

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();
}
Run Code Online (Sandbox Code Playgroud)