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.

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) body.appendParagraph(element);
      else if (type == DocumentApp.ElementType.TABLE) body.appendTable(element);
      else if (type == DocumentApp.ElementType.LIST_ITEM) body.appendListItem(element);
      else 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.

Amit Agarwal is a web geek, solo entrepreneur and loves making things on the Internet. Google recently awarded him the Google Developer Expert and Google Cloud Champion title for his work on Google Workspace and Google Apps Script.

Awards & Recognition

Google Developer Expert

Google Developer Expert

Google awarded us the Developer Expert title recogizing our work in Workspace

ProductHunt Golden Kitty

ProductHunt Golden Kitty

Our Gmail tool won the Lifehack of the Year award at ProductHunt Golden Kitty Awards

Microsoft MVP Alumni

Microsoft MVP Alumni

Microsoft awarded us the Most Valuable Professional title for 5 years in a row

Google Cloud Champion

Google Cloud Champion

Google awarded us the Champion Innovator award for technical expertise

Want to stay up to date?
Sign up for our email newsletter.

We will never send any spam emails. Promise 🫶🏻