Merge Word Documents with JavaScript in React

2026-07-06 08:28:38 Written by  Amy Zhao
Rate this item
(0 votes)

Combining several contract attachments into one complete document, appending supplementary content at the end of a report, or merging multiple chapters into a single output — these requirements are common in web applications. Handling them on the server means files must first be uploaded and leave the user's device; asking users to install desktop software and stitch documents together by hand is equally hard to fit into a batch-oriented web workflow.

This article uses Spire.Doc for JavaScript to merge Word documents directly in the browser. The whole process runs client-side on WebAssembly, requires no Office installation and no backend, and reads and writes documents locally through a virtual file system (VFS), so files stay on the user's device the entire time.

This article covers two core features:

For installation and project configuration, refer to Integrating Spire.Doc for JavaScript in a React Project. The examples below assume Spire.Doc has been installed and the WebAssembly module has been initialized.


Merge Word Documents by Section

Spire.Doc for JavaScript appends a section to the end of the target document with the Sections.Add() method, and Section.Clone() makes it possible to copy a section without modifying the source document. A cloned section keeps its own page setup, so in the merged document it usually starts on a new page.

The steps are as follows:

  1. Obtain the Spire.Doc WASM module and confirm that it is ready.
  2. Read both sample Word documents into VFS, create a Document object and load the target document.
  3. Create another Document object and load the source document.
  4. Iterate over the source document's Sections collection and use Sections.Add(section.Clone()) to clone each section and append it to the end of the target document.
  5. Save the result with the Document.SaveToFile() method.
  6. Read the result file back from VFS and trigger a browser download.

The code for merging Word documents by section is as follows:

function App() {
  const mergeBySection = async () => {
    // Get the Spire.Doc WASM module
    const docModule = window.wasmModule?.spiredoc;

    // Check if the module is ready
    if (!docModule) {
      alert('Spire.Doc is not ready yet');
      return;
    }
    
    // Read both sample documents into VFS
    const inputFileName1 = 'Template_Docx_1.docx';
    await window.spire.FetchFileToVFS(inputFileName1, '', `${process.env.PUBLIC_URL}static/data/`);
    const inputFileName2 = 'Template_Docx_2.docx';
    await window.spire.FetchFileToVFS(inputFileName2, '', `${process.env.PUBLIC_URL}static/data/`);

    // Load the target document
    const TarDoc = new docModule.Document();
    TarDoc.LoadFromFile(inputFileName1);

    // Load the source document
    const SouDoc = new docModule.Document();
    SouDoc.LoadFromFile(inputFileName2);

    // Clone every section of the source document and append it to the end of the target document
    for (let i = 0; i < SouDoc.Sections.Count; i++) {
      let section = SouDoc.Sections.get_Item(i);
      TarDoc.Sections.Add(section.Clone());
    }

    // Define the output file name
    const outputFileName = 'MergeBySection_out.docx';

    // Save the merged document
    TarDoc.SaveToFile({ fileName: outputFileName, fileFormat: docModule.FileFormat.Docx2013 });

    // Read the merged file from VFS and trigger the download
    const modifiedFileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
    const blob = new Blob([modifiedFileArray], { type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = outputFileName;
    a.click();
    URL.revokeObjectURL(url);

    // Release resources
    TarDoc.Dispose();
    SouDoc.Dispose();
  };

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Merge Word Documents by Section</h1>
      <button onClick={mergeBySection}>
        Merge Documents
      </button>
    </div>
  );
}

export default App;

After merging by section, each section of the source document occupies its own page in the target document:

After merging by section, each section of the source document occupies its own page in the target document

Merge Only Selected Sections from the Source Document

If only a few sections of the source document are required, there is no need to iterate over the entire Sections collection; retrieve the desired section by index and clone it:

// Clone only the first section of the source document and append it to the end of the target document
const section = SouDoc.Sections.get_Item(0);
TarDoc.Sections.Add(section.Clone());

Merge Word Documents on the Same Page

Same-page merging differs from section-by-section merging in that it does not create new sections for the source document. Instead, it clones the paragraphs, tables, images and other elements of the source document one by one and appends them to the same section of the target document. The two approaches map to the following APIs:

Approach Content Appended Pagination
Sections.Add(section.Clone()) A complete section of the source document Each section starts on a new page
Body.ChildObjects.Add(obj.Clone()) One content element from a section of the source document Content flows continuously without creating a new section

The steps are as follows:

  1. Obtain the Spire.Doc WASM module and confirm that it is ready.
  2. Read both sample Word documents into VFS, create a Document object and load the target document.
  3. Record the target document's current section count so that the last section can be located.
  4. Create another Document object and load the source document, then iterate over the Body.ChildObjects of each of its sections with two nested loops.
  5. Use ChildObjects.Add(obj.Clone()) to append each content element to the end of the last section's ChildObjects collection in the target document.
  6. Save the result with the Document.SaveToFile() method.
  7. Read the result file back from VFS and trigger a browser download.

The code for merging Word documents on the same page is as follows:

function App() {
  const mergeOnSamePage = async () => {
    // Get the Spire.Doc WASM module
    const docModule = window.wasmModule?.spiredoc;

    // Check if the module is ready
    if (!docModule) {
      alert('Spire.Doc is not ready yet');
      return;
    }

	// Read both sample documents into VFS
    const inputFileName1 = 'Template_Docx_1.docx';
    await window.spire.FetchFileToVFS(inputFileName1, '', `${process.env.PUBLIC_URL}static/data/`);
    const inputFileName2 = 'Template_Docx_2.docx';
    await window.spire.FetchFileToVFS(inputFileName2, '', `${process.env.PUBLIC_URL}static/data/`);
    
    // Load the target document
    const destinationDocument = new docModule.Document();
    destinationDocument.LoadFromFile(inputFileName1);

    // Record the current section count of the target document
    let count = destinationDocument.Sections.Count;

    // Load the source document
    const doc = new docModule.Document();
    doc.LoadFromFile(inputFileName2);

    // Iterate over every content element of the source document and clone it into the last section of the target document
    for (let i = 0; i < doc.Sections.Count; i++) {
      let section = doc.Sections.get_Item(i);
      for (let j = 0; j < section.Body.ChildObjects.Count; j++) {
        let obj = section.Body.ChildObjects.get_Item(j);
        destinationDocument.Sections.get_Item(count - 1).Body.ChildObjects.Add(obj.Clone());
      }
    }

    // Define the output file name
    const outputFileName = 'MergeOnSamePage_out.docx';

    // Save the merged document
    destinationDocument.SaveToFile({ fileName: outputFileName, fileFormat: docModule.FileFormat.Docx2013 });

    // Read the merged file from VFS and trigger the download
    const modifiedFileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
    const blob = new Blob([modifiedFileArray], { type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = outputFileName;
    a.click();
    URL.revokeObjectURL(url);

    // Release resources
    destinationDocument.Dispose();
    doc.Dispose();
  };

  return (
    <div style={{ textAlign: 'center', height: '300px' }}>
      <h1>Merge Word Documents on the Same Page</h1>
      <button onClick={mergeOnSamePage}>
        Merge Documents
      </button>
    </div>
  );
}

export default App;

After same-page merging, the source document's content is appended continuously to the last section of the target document, producing no page breaks:

After same-page merging, the source document's content is appended continuously to the last section of the target document, producing no page breaks


FAQ

Will the merged file be uploaded to a server?

No. Spire.Doc for JavaScript runs in the browser on WebAssembly, reads and writes documents locally through a virtual file system (VFS), and performs merging and saving entirely on the client; the library itself never sends files to a server. Whether the file ultimately leaves the device depends on any other code you add to the page.

Can multiple Word documents be merged at once?

Yes — simply process them in a loop. Load each source document in turn; when merging by section, call Sections.Add(section.Clone()) for every section of every source document, and when merging on the same page, loop over Body.ChildObjects for each source document. With a large number of documents, keep an eye on browser memory and call Dispose() promptly to release Document objects that are no longer needed.

Why does the source content start on a new page after merging by section?

Cause: Section.Clone() copies a complete section, including its own page setup. Once the section is appended to the target document, the merged content therefore usually starts on a new page.

Solution: When the content has to flow continuously, switch to same-page merging and append the source document's paragraphs, tables and other elements one by one to the last section of the target document:

// Append element by element without creating a new section
destinationDocument.Sections.get_Item(count - 1).Body.ChildObjects.Add(obj.Clone());

What should I do if the merged Word document cannot be opened?

Cause: The save format does not match the file extension, or the Blob's MIME type does not match the actual file format at download time, so the browser or Word may fail to identify the file correctly.

Solution: Keep the save format, the extension and the MIME type consistent. When fileFormat in SaveToFile() is Docx2013, keep the .docx extension in the output file name and use the corresponding DOCX type for the Blob's type:

const blob = new Blob([fileArray], {
  type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
});

Are images and tables preserved after merging?

Generally yes. Merging by section clones whole sections, while same-page merging clones the paragraphs, tables and other child objects under a section's Body; this content is written to the target document along with the clone, and images inside paragraphs are usually preserved as well. After merging, open the result file to check the layout.


Get a Free License

Spire.Doc for JavaScript offers a 30-day full-featured free trial license with no functional limitations. Apply here to evaluate before purchasing.

Additional Info

  • tutorial_title:
Last modified on Friday, 23 October 2026 06:17