<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ merging - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ merging - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Thu, 25 Jun 2026 10:02:28 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/merging/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How to Merge Multiple Google Docs into One ]]>
                </title>
                <description>
                    <![CDATA[ Merging multiple Google Docs into a single document is often essential for compiling reports, gathering information from various sources, or creating unified documents for presentations or sharing. By combining multiple files into one, users can keep... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/merge-multiple-google-docs-with-apps-script-or-google-docs-api/</link>
                <guid isPermaLink="false">672103feae01d783da13018b</guid>
                
                    <category>
                        <![CDATA[ Google Docs ]]>
                    </category>
                
                    <category>
                        <![CDATA[ APIs ]]>
                    </category>
                
                    <category>
                        <![CDATA[ merging ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Vikram Aruchamy ]]>
                </dc:creator>
                <pubDate>Tue, 29 Oct 2024 15:49:18 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1730115525086/d5d63d7d-a5c0-4e16-868c-50901aebb248.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Merging multiple Google Docs into a single document is often essential for compiling reports, gathering information from various sources, or creating unified documents for presentations or sharing.</p>
<p>By combining multiple files into one, users can keep information organized, streamline collaboration, and simplify document handling for larger projects or recurring tasks.</p>
<p>But Google Docs lacks a built-in feature for merging multiple documents. This can make this process time-consuming if you’re trying to do it manually.</p>
<p>While there are add-ons available for <a target="_blank" href="https://workspace.google.com/marketplace/app/merge_docs_pro/61337277026">merging multiple Google Docs into one</a>, you can also create your own scripts using Google Apps Script or the Google Docs API for customized solutions. This approach gives you greater flexibility, letting you set up recurring document consolidation and manage high volumes of merges tailored to your specific needs.</p>
<p>In this tutorial, I’ll explain how to merge multiple Google Docs into one document using <a target="_blank" href="https://developers.google.com/apps-script">Apps Script</a> or the <a target="_blank" href="https://developers.google.com/docs/api/reference/rest">Google Docs API</a>.</p>
<h2 id="heading-how-to-merge-google-docs-using-google-apps-script">How to Merge Google Docs Using Google Apps Script</h2>
<p>Using Google Apps Script to merge multiple Google Docs is a straightforward way to automate document merging directly within Google Workspace.</p>
<p>This approach should work well for you if you need a simple solution that doesn’t require complex setups or external APIs. You can run Apps Script within Google Drive, making it easy to set up and execute directly from the browser.</p>
<p>Below is a step-by-step guide on how to use Google Apps Script for merging documents.</p>
<h3 id="heading-step-1-open-google-apps-script"><strong>Step 1: Open Google Apps Script</strong></h3>
<p>In Google Drive, click on <strong>New</strong> &gt; <strong>Google Apps Script</strong> to create a new script.</p>
<p>Then name the project something relevant, like “Document Merger.”</p>
<h3 id="heading-step-2-write-the-apps-script-code"><strong>Step 2: Write the Apps Script Code</strong></h3>
<p>Copy and paste the following code into the Apps Script editor. This script will create a new Google Doc and append content from each specified document.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">mergeGoogleDocs</span>(<span class="hljs-params">docIds</span>) </span>{
  <span class="hljs-keyword">const</span> mergedDoc = DocumentApp.create(<span class="hljs-string">"Merged Document"</span>); <span class="hljs-comment">// Creates a new document</span>
  <span class="hljs-keyword">const</span> body = mergedDoc.getBody();

  docIds.forEach(<span class="hljs-function"><span class="hljs-params">id</span> =&gt;</span> {
    <span class="hljs-keyword">const</span> doc = DocumentApp.openById(id);
    <span class="hljs-keyword">const</span> docBody = doc.getBody();

    <span class="hljs-comment">// Append content of each document to the merged document</span>
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; docBody.getNumChildren(); i++) {
      <span class="hljs-keyword">const</span> element = docBody.getChild(i).copy(); <span class="hljs-comment">// Copy each element to preserve formatting</span>
      body.appendParagraph(element.getText());
    }
    body.appendPageBreak(); <span class="hljs-comment">// Add a page break after each document</span>
  });

  Logger.log(<span class="hljs-string">"Merged Document URL: "</span> + mergedDoc.getUrl());
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">runMerge</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> docIds = [
    <span class="hljs-string">'DOCUMENT_ID_1'</span>, 
    <span class="hljs-string">'DOCUMENT_ID_2'</span>, 
    <span class="hljs-string">'DOCUMENT_ID_3'</span>
  ]; <span class="hljs-comment">// Replace with your actual document IDs</span>

  mergeGoogleDocs(docIds);
}
</code></pre>
<p><strong>Explanation of the Code:</strong></p>
<ul>
<li><p><strong>Creating the Merged Document</strong>: <code>DocumentApp.create("Merged Document")</code> creates a new Google Doc named "Merged Document," which will serve as the destination for all the content.</p>
</li>
<li><p><strong>Retrieving and Copying Content</strong>: <code>DocumentApp.openById(id)</code> opens each document in <code>docIds</code>, then retrieves its body content. The script copies each element, preserving its original formatting, and appends it to the new document.</p>
</li>
<li><p><strong>Adding Page Breaks</strong>: <code>body.appendPageBreak()</code> adds a page break after each document, helping maintain a clear separation between merged sections.</p>
</li>
<li><p><strong>Logging the Merged Document URL</strong>: The final URL of the merged document is logged, allowing you to access it directly from the Apps Script console.</p>
</li>
</ul>
<h3 id="heading-step-3-run-the-script"><strong>Step 3: Run the Script</strong></h3>
<p>First, you’ll want to save the script and authorize any required permissions.</p>
<p>Then in the Apps Script editor, select <code>runMerge()</code> as the function to run. Enter an array of document IDs you want to merge, like <code>['DOCUMENT_ID_1', 'DOCUMENT_ID_2', 'DOCUMENT_ID_3']</code>.</p>
<p>Finally, run the script, and it will create a merged document in your Google Drive. The URL will display in the console log.</p>
<h3 id="heading-how-to-customize-the-script"><strong>How to Customize the Script</strong></h3>
<p><strong>Order of Documents</strong>: The sequence in which documents are merged is controlled by the order of <code>docIds</code> in the array. Arrange these document IDs to define the exact order you want in the final document.</p>
<p>This approach is useful for structuring documents such as reports, books, or presentations, ensuring that chapters or sections appear in the intended flow.</p>
<p><strong>Adding Custom Formatting</strong>: The script can be customized to add specific formatting to each section of the merged document. You can insert headers or footers to distinguish each document, include page breaks, or set up consistent styling for fonts, sizes, and colors.</p>
<p>For example, you can add headers programmatically at the start of each new document in the merge, helping create a cohesive structure.</p>
<p><strong>Handling Specific Elements</strong>: Apps Script supports detailed customization to merge only certain types of content, like text, images, or tables, while skipping others. You can adjust the script to filter out elements by type or to prioritize specific formats.</p>
<p>For instance, to create a visually appealing document, you might choose to merge only text and images while excluding tables or unsupported elements. This approach provides a more polished final document by focusing on the content types you need most.</p>
<h3 id="heading-when-to-use-google-apps-script-for-merging"><strong>When to Use Google Apps Script for Merging</strong></h3>
<p>Google Apps Script is ideal if you want a simple, in-drive solution without needing to set up external API access. It’s especially useful for quick merges or individual projects within Google Workspace, and it provides enough flexibility to handle most standard document formats and structures.</p>
<p>For more complex requirements, such as merging across other platforms or integrating with external tools, consider using the Google Docs API explained in the next section.</p>
<h2 id="heading-how-to-merge-google-docs-using-the-google-docs-api">How to Merge Google Docs Using the Google Docs API</h2>
<p>Combining Google Docs using the Google Docs API allows you to programmatically combine content from multiple documents into one unified file. This is ideal for automating repetitive merges or creating customized documents on demand.</p>
<p>This approach is powerful for users who need precise control over document content, formatting, and layout, making it suitable for larger workflows or integrations within other applications.</p>
<p>Below is a detailed, step-by-step guide on how to use the Google Docs API to merge multiple Google Docs into one.</p>
<h3 id="heading-step-1-enable-the-google-docs-api"><strong>Step 1: Enable the Google Docs API</strong></h3>
<p>First, go to the <a target="_blank" href="https://console.cloud.google.com/">Google Cloud Console</a>. Create a new project or select an existing one.</p>
<p>In the API Library, search for "Google Docs API" and enable it for your project.</p>
<p>Next, create OAuth 2.0 credentials by going to <strong>APIs &amp; Services</strong> &gt; <strong>Credentials</strong>. Choose <strong>Create Credentials</strong> &gt; <strong>OAuth client ID</strong> and configure this for a Web Application if you plan to integrate it into Web services.</p>
<h3 id="heading-step-2-install-the-googleapis-client-library"><strong>Step 2: Install the</strong> <code>googleapis</code> <strong>Client Library</strong></h3>
<p>In a Node.js environment, you’ll need the <code>googleapis</code> package to interact with the Google Docs API. Install it by running:</p>
<pre><code class="lang-bash">npm install googleapis
</code></pre>
<h3 id="heading-step-3-write-the-script-to-merge-google-docs"><strong>Step 3: Write the Script to Merge Google Docs</strong></h3>
<p>The following script uses the Google Docs API to create a new document, retrieve content from each source document, and then append this content to the new document.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> { google } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'googleapis'</span>);
<span class="hljs-keyword">const</span> docs = google.docs(<span class="hljs-string">'v1'</span>);

<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">mergeGoogleDocs</span>(<span class="hljs-params">auth, docIds</span>) </span>{
  <span class="hljs-comment">// Step 3a: Create a new document that will serve as the merged document</span>
  <span class="hljs-keyword">const</span> newDoc = <span class="hljs-keyword">await</span> docs.documents.create({
    auth,
    <span class="hljs-attr">requestBody</span>: { <span class="hljs-attr">title</span>: <span class="hljs-string">'Merged Document'</span> },
  });
  <span class="hljs-keyword">const</span> newDocId = newDoc.data.documentId;

  <span class="hljs-comment">// Step 3b: Loop through each document ID, retrieving content and appending it to the new document</span>
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> docId <span class="hljs-keyword">of</span> docIds) {
    <span class="hljs-comment">// Retrieve the document's body content</span>
    <span class="hljs-keyword">const</span> doc = <span class="hljs-keyword">await</span> docs.documents.get({
      auth,
      <span class="hljs-attr">documentId</span>: docId,
    });

    <span class="hljs-comment">// Prepare each content element as a request for the new document</span>
    <span class="hljs-keyword">const</span> requests = doc.data.body.content.map(<span class="hljs-function">(<span class="hljs-params">element</span>) =&gt;</span> ({
      <span class="hljs-attr">insertText</span>: {
        <span class="hljs-attr">text</span>: element.paragraph?.elements?.[<span class="hljs-number">0</span>]?.textRun?.content || <span class="hljs-string">''</span>,
        <span class="hljs-attr">location</span>: { <span class="hljs-attr">index</span>: <span class="hljs-number">1</span> }, <span class="hljs-comment">// Append to the start of the document, shift with each insertion</span>
      },
    }));

    <span class="hljs-comment">// Send a batch update request to insert all elements into the new document</span>
    <span class="hljs-keyword">await</span> docs.documents.batchUpdate({
      auth,
      <span class="hljs-attr">documentId</span>: newDocId,
      <span class="hljs-attr">requestBody</span>: { requests },
    });
  }

  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Merged Document URL: https://docs.google.com/document/d/<span class="hljs-subst">${newDocId}</span>`</span>);
}
</code></pre>
<p><strong>Explanation of the Code:</strong></p>
<ol>
<li><p><strong>Creating the Merged Document</strong>: <code>docs.documents.create()</code> creates a new Google Doc titled "Merged Document." This document ID (<code>newDocId</code>) will serve as the destination where content from each document is appended.</p>
</li>
<li><p><strong>Retrieving Content</strong>: The <code>docs.documents.get()</code> method fetches each document’s content based on its ID. This retrieves all elements from the document body, such as paragraphs, images, and other supported elements.</p>
</li>
<li><p><strong>Preparing Insert Requests</strong>: The <code>map()</code> function converts each document element into an <code>insertText</code> request. Each request specifies the text and the location in the new document where it should be added.</p>
</li>
<li><p><strong>Appending Text in Sequence</strong>: The <code>batchUpdate</code> method takes a set of requests and applies them sequentially to the new document. Here, the location index starts at 1 (the beginning of the document) and shifts with each new insertion to prevent overwriting.</p>
</li>
</ol>
<h3 id="heading-step-4-run-the-script"><strong>Step 4: Run the Script</strong></h3>
<p>Now you’ll initialize the <code>auth</code> variable with <a target="_blank" href="https://developers.google.com/identity/protocols/oauth2">OAuth 2.0 credentials</a>, which authenticates access to the Docs API.</p>
<p>Then you’ll need to call the <code>mergeGoogleDocs</code> function, passing the <code>auth</code> object and an array of document IDs.</p>
<p>Once the script runs, it will output a URL for the merged document, which you can access directly in Google Docs.</p>
<h3 id="heading-customization-and-additional-options"><strong>Customization and Additional Options</strong></h3>
<ul>
<li><p><strong>Order of Insertion</strong>: Control the order in which document content is appended by arranging the document IDs in <code>docIds</code>.</p>
</li>
<li><p><strong>Formatting</strong>: The Google Docs API can support additional formatting, such as bold or italic text, by modifying the insert requests. This can be achieved with advanced requests using the <code>updateTextStyle</code> API method.</p>
</li>
<li><p><strong>Element Types</strong>: The script currently handles only text paragraphs. To merge other elements like images or tables, extend the script to support more element types by using conditional checks on the <code>element</code> structure.</p>
</li>
</ul>
<h3 id="heading-when-to-use-google-docs-api-for-merging"><strong>When to Use Google Docs API for Merging</strong></h3>
<p>The Google Docs API is ideal if you need precise control over document structure, element-specific formatting, and larger-scale automation for merging.</p>
<p>This approach is especially useful when handling complex formatting requirements, such as custom headers, lists, or tables, and allows for seamless integration with external applications or workflows outside Google Workspace.</p>
<p>If you have high-volume merge needs or you’re looking to incorporate merging into broader, automated processes, the Google Docs API provides advanced flexibility and customization options beyond what Google Apps Script can offer.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In conclusion, merging Google Docs is crucial for organizing and streamlining document management. While Google Docs lacks a built-in feature for this, you can leverage Google Apps Script for straightforward automation or the Google Docs API for more advanced, large-scale merging.</p>
<p>For those seeking a user-friendly solution without the need for coding, <a target="_blank" href="https://www.mergedocs.pro/"><strong>Merge Docs Pro</strong></a> provides an intuitive interface to combine multiple Google Docs into one document. It simplifies document consolidation, enhances collaboration, and saves time, making it an excellent choice if you’re looking to streamline your workflow within Google Workspace.</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
