How to merge word documents

Tags: Open XML SDK, Open XML, Merge word documents, DocumentBuilder Sample, PowerTools for Open XML, Microsoft Word, Word, Word 2007, Office, Office Document

One of the option to merge word documents if you are using Office 2007 and up is using the DocumentBuilder (a class in PowerTools for Open XML).

PowerTools for Open XML is an open source library that helps you to:

“accomplishing various common tasks using the Open XML SDK, such as:

  • High-fidelity conversion of DOCX to HTML/CSS using HtmlConverter.cs
  • Merging and splitting DOCX documents using DocumentBuilder.cs
  • Merging and splitting PPTX presentations using PresentationBuilder.cs
  • Accepting tracked revisions in DOCX documents using RevisionAccepter.cs
  • Searching and replacing text in DOCX documents using TextReplacer.cs”


Here’s a code sample performing simple merging of files:

public void MergeDocuments(string[] fileNames, string outputFilePath)
{
    using (var outputFileStream = new FileStream(outputFilePath, FileMode.Create, FileAccess.ReadWrite))
    {
        var sources = new List<Source>();

        foreach (string fileName in fileNames)
        {
            byte[] allBytes = File.ReadAllBytes(fileName);

            var openXmlPowerToolsDocument = new OpenXmlPowerToolsDocument(allBytes);

            var source = new Source(new WmlDocument(openXmlPowerToolsDocument), true);

            sources.Add(source);
        }

        MergeXmlDocuments(outputFileStream, sources);
    }

}

public void MergeXmlDocuments(Stream outStream, List<Source> sources)
{
    WmlDocument buildDocument = DocumentBuilder.BuildDocument(sources);
    buildDocument.WriteByteArray(outStream);
}

No Comments

Add a Comment