How to copy a template and insert content from another document?

妖精的绣舞 提交于 2019-12-03 08:37:47
Serge insas

I guess the only way is to copy elements one by one... there are a whole bunch of document elements but it shouldn't be too hard to be quite exhaustive. Here is how it goes for the most common types, you'll have to add the other ones.

(original code borrowed from an answer by Henrique Abreu)

function importInDoc() {
  var docID = 'id of the template copy';
  var baseDoc = DocumentApp.openById(docID);
  var body = baseDoc.getBody();

  var otherBody = DocumentApp.openById('id of source document').getBody();
  var totalElements = otherBody.getNumChildren();
  for( var j = 0; j < totalElements; ++j ) {
    var element = otherBody.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);
    else if( type == DocumentApp.ElementType.INLINE_IMAGE )
      body.appendImage(element);

    // add other element types as you want

    else
      throw new Error("According to the doc this type couldn't appear in the body: "+type);
  }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!