How can I merge documents with Google Apps Script while keeping the order and proper sequencing of numbered lists?

52 Views Asked by At

I have a script to merge a few google docs together. While most of the formatting is preserved, the lists are not continuous and show up like this in the master document:

A. xxx  
    1. xxx  
    1. xxx  
      i. xxx  
      i. xxx  
A. xxx  
etc.

How can I correct the code to have the numbered lists work properly?

I have tried the code below, which merges the second and third documents in docID into the master file in docID [0] It results in the lists having issues as shown and the sequencing is not preserved. I was also hoping that the sequencing would be preserved between documents but not sure how that would be implemented. Ideally:

Doc 1

A  
   1 ...  
   2 ...  
B   
   ...  
C  
   ...  

Doc 2

A  
B  

would merge in the master document to go from A to E.

I've appended what I have so far.

function mergeGoogleDocs() {
  var docIDs = ['xxxx' , 'xxxx', 'xxxx'];
  var baseDoc = DocumentApp.openById(docIDs[0]);

  var body = baseDoc.getActiveSection();
  // Clear existing content in the master document
  baseDoc.getBody().clear();

  for (var i = 1; i < docIDs.length; ++i) {
    var otherBody = DocumentApp.openById(docIDs[i]).getActiveSection();
    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.asListItem().getText()).setAttributes(element.getAttributes());
      else throw new Error('Unknown element type: ' + type);
    }
  }
}
0

There are 0 best solutions below