How to Merge Multiple Google Documents

You can use Google Apps Script to merge two or more Google Documents into a single document. The script takes the first document and appends the content of all the other documents into this document. All the formatting, tables, lists and other elements are preserved in the merged document.

/* Snippet from */

function mergeGoogleDocs() {

  var docIDs = ['documentID_1','documentID_2','documentID_3','documentID_4'];
  var baseDoc = DocumentApp.openById(docIDs[0]);

  var body = baseDoc.getActiveSection();

  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 )
      else if( type == DocumentApp.ElementType.TABLE )
      else if( type == DocumentApp.ElementType.LIST_ITEM )
        throw new Error("Unknown element type: "+type);

Update: [Merijn Peeters] My document included a very big table, and when merging several of those documents, a blank line was added from the second page onward. This corrupted the layout, of course.

After hours of searching, I discovered that the error was due to the fact that the 'appendTable' function automatically appends a blank paragraph as well, because a document cannot end with a table. From Google's documentation:

appendTable() - Creates and appends a new Table - This method will also append an empty paragraph after the table, since Google Docs documents cannot end with a table.