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

雨燕双飞 提交于 2019-12-04 13:17:32

问题


I want to write a Google Docs script that copies a template (which just contains a container bound script) and appends the contents of another document chosen by the user. How would I accomplish this? I already have a way to select the file (the template has a static id), but figure out a way to copy all the content of the document (including inlineImages and hyperLinks) to the my new document.


回答1:


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


来源:https://stackoverflow.com/questions/19349641/how-to-copy-a-template-and-insert-content-from-another-document

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!