Search code examples
google-apps-scriptgoogle-docs

Google Apps Script fails to copy bullets from one document to other document


Following this code, I am using Google Apps Script to append a document template to another document. The template has bullets lists, however these will be lost upon copy, while indentation will be retained correctly.

Link to the template

Code:

     var newDoc = DocumentApp.openById('anotherGoogleID');
      var newDocBody = newDoc.getBody();
      var templateBody = DocumentApp.openById('aGoogleID').getActiveSection();
 // has bullets
          var totalElements = templateBody.getNumChildren();
          newDocBody.appendPageBreak();
          for( var j = 0; j < totalElements; ++j ) {
            var element = otherBody.getChild(j).copy();
            var type = element.getType();
            if( type == DocumentApp.ElementType.PARAGRAPH )
              newDocBody.appendParagraph(element);
            else if( type == DocumentApp.ElementType.TABLE )
              newDocBody.appendTable(element);
            else if( type == DocumentApp.ElementType.LIST_ITEM )
              newDocBody.appendListItem(element);
            else
              throw new Error("Unknown element type: "+type);
          }
    newDocBody.saveAndClose()

Solution

  • I found I could get it to work with

    newDocBody.appendListItem(listItem.getText()).setAttributes(element.getAttributes()); 
    

    To put it in context: (based of https://www.labnol.org/code/19892-merge-multiple-google-documents)

    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).setAttributes(element.getAttributes());             
        else if( type == DocumentApp.ElementType.TABLE )
          body.appendTable(element).setAttributes(element.getAttributes());
        else if( type == DocumentApp.ElementType.LIST_ITEM ){ 
          var listItem = element.asListItem();
        body.appendListItem(listItem.getText()).setAttributes(element.getAttributes());            
    }