DEV Community

jelizaveta
jelizaveta

Posted on

Merging Multiple Word Documents into a Single PDF with C#

Merging multiple Word documents into a single PDF file makes it convenient for distribution, printing, or archiving. This article introduces how to use the Spire.Doc for .NET library to easily merge all Word documents in a specified folder and export them to PDF with just a few lines of concise C# code.

As a professional .NET Word component, Spire.Doc for .NET allows developers to efficiently create, edit, convert, and print Word documents without installing Microsoft Office, offering excellent stability and scalability.

Preparation: Install Spire.Doc

First, install the Spire.Doc library in your .NET project. It is recommended to install it via the NuGet Package Manager for quick and convenient setup.

You can search for Spire.Doc in Visual Studio's "Manage NuGet Packages" and install it, or execute the following command in the "Package Manager Console":

PM> Install-Package Spire.Doc
Enter fullscreen mode Exit fullscreen mode

Code Implementation: Merging and Conversion

The core logic is straightforward: create a new Document object to hold the final merged content; read all Word files in the folder; load the first document as the base; then loop through and insert the remaining documents; and finally save the result as a PDF.

Here is the complete code example:

using System.IO;
using System.Linq;
using Spire.Doc;

namespace MergeWordFolder
{
    class Program
    {
        static void Main(string[] args)
        {
            // 1. Create the target document container
            Document mergedDocument = new Document();

            // 2. Get all Word documents in the specified folder
            string folderPath = @"Documents"; // Replace with your folder path
            string[] files = Directory.GetFiles(folderPath, "*.docx")
                                      .OrderBy(f => f)
                                      .ToArray();

            // Check if there are any files
            if (files.Length == 0)
            {
                Console.WriteLine("No .docx files found in the folder.");
                return;
            }

            // 3. Load the first document as the base
            mergedDocument.LoadFromFile(files[0], FileFormat.Docx);

            // 4. Insert the remaining documents sequentially
            for (int i = 1; i < files.Length; i++)
            {
                // The InsertTextFromFile method appends the entire content of a document to the end of the current document
                mergedDocument.InsertTextFromFile(files[i], FileFormat.Docx);
            }

            // 5. Save the merged document as PDF
            mergedDocument.SaveToFile("MergedDocument.pdf", FileFormat.PDF);

            Console.WriteLine("Merge complete! MergedDocument.pdf has been generated.");
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Code Breakdown

  1. Create the document object : Document mergedDocument = new Document(); instantiates a blank Word document object that will serve as the final container for all merged content.
  2. Get the file list : Directory.GetFiles(folderPath, "*.docx") retrieves all files with the .docx extension in the specified path. .OrderBy(f => f) ensures files are merged in alphabetical order by name, preventing order confusion. You can adjust the sorting logic as needed.
  3. Load and insert :
    • mergedDocument.LoadFromFile(files[0], FileFormat.Docx): Loads the first Word document into the blank container we created.
    • mergedDocument.InsertTextFromFile(files[i], FileFormat.Docx): This is a highly efficient method. In the loop, it inserts the entire content of each subsequent Word document (including text, images, tables, headers, footers, etc.) directly to the end of mergedDocument.
  4. Save as PDF : mergedDocument.SaveToFile("MergedDocument.pdf", FileFormat.PDF) is the final and most critical step. It outputs the merged Document object directly as a PDF file, achieving a one-stop operation from "merging" to "conversion."

Summary and Extensions

With the simple code above, we successfully avoid the tedious process of manually opening, copying, pasting, and then saving as PDF. The Spire.Doc library is highly efficient in handling such document merging tasks.

Beyond merging .docx files, this method offers strong extensibility. For example, if you need to merge .doc files, simply modify the search pattern in Directory.GetFiles and specify the corresponding FileFormat in the LoadFromFile and InsertTextFromFile methods.

Top comments (0)