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
Google Developer Expert, Google Cloud Champion
Amit Agarwal is a Google Developer Expert in Google Workspace and Google Apps Script. He holds an engineering degree in Computer Science (I.I.T.) and is the first professional blogger in India.
Amit has developed several popular Google add-ons including Mail Merge for Gmail and Document Studio. Read more on Lifehacker and YourStory