How to combine multiple files into single document using C# and .NET


Here we'll show you how to merge: PDF, DOCX, Txt in single PDF file

A few steps:

  1. Notice you are importing the SautinSoft.Document namespace.
    using SautinSoft.Document;
  2. First of all, you must specify, where to get the files for converting and a format of these files (*.docx, *.pdf, *.txt).
    
                 // Working directory
                string workingDir = Path.GetFullPath(@"d:\Tempos\MergeFiles\");
    
                // Path to our combined document.
                string singlePDFPath = Path.Combine(workingDir, "Single.pdf");
                // Remove it if our combined document is already exist.
                if (File.Exists(singlePDFPath))
                    File.Delete(singlePDFPath);
    
                List<string> supportedFiles = new List<string>();
    
                // Fill the collection 'supportedFiles' by *.docx, *.pdf and *.txt.
                foreach (string file in Directory.GetFiles(workingDir, "*.*"))
                {
                    string ext = Path.GetExtension(file).ToLower();
    
                    if (ext == ".docx" ||  ext == ".pdf" || ext == ".txt")
                        supportedFiles.Add(file);
                }
    
  3. For example: We need to merge 1.txt, 2.docx, 3.pdf
  4. The next step is to combine ALL found files into single document.
    Because we are copying a section from one document to another, it is required to import the Section into the destination document.
    This adjusts any document-specific references to styles, bookmarks, etc.
    
                foreach (string file in supportedFiles)
                {
                    DocumentCore document = DocumentCore.Load(file);
    
                    Console.WriteLine("Adding: {0}...", Path.GetFileName(file));
    
                    // Create import session.
                    ImportSession session = new ImportSession(document, singlePDF, StyleImportingMode.UseDestinationStyles);
    
                    // Loop through all sections in the source document.
                    foreach (Section sourceSection in document.Sections)
                    {
                        Section importedSection = singlePDF.Import<Section>(sourceSection, true, session);
                        // Now the new section can be appended to the destination document.
                        singlePDF.Sections.Add(importedSection);
                    }
                }
                            
  5. We combined all the files into one document. Now save it as PDF
    By the way, you can save these files as DOCX, RTF, Text.
    
                // Save single PDF to a file.            
                singlePDF.Save(singlePDFPath);
    
  6. Download the resulting PDF-file: Single.pdf
 

Complete code

using System;
using System.IO;
using System.Collections.Generic;
using SautinSoft.Document;

namespace Sample
{
    class Sample
    {

        static void Main(string[] args)
        {
            // Get your free 30-day key here:   
            // https://sautinsoft.com/start-for-free/

            MergeMultipleDocuments();
        }

		/// <summary>
        /// This sample shows how to merge multiple DOCX, RTF, PDF and Text files.
        /// </summary>
		/// <remarks>
        /// Details: https://sautinsoft.com/products/document/help/net/developer-guide/merge-multiple-files-net-csharp-vb.php
        /// </remarks>
        public static void MergeMultipleDocuments()
        {
            // Path to our combined document.
            string singlePDFPath = "Single.pdf";
            string workingDir = @"..\..\..\";

            List<string> supportedFiles = new List<string>();
            // Fill the collection 'supportedFiles' by *.docx, *.pdf and *.txt.
            foreach (string file in Directory.GetFiles(workingDir, "*.*"))
            {
                string ext = Path.GetExtension(file).ToLower();

                if (ext == ".docx" || ext == ".pdf" || ext == ".txt")
                    supportedFiles.Add(file);
            }


            // Create single pdf.
            DocumentCore singlePDF = new DocumentCore();

            foreach (string file in supportedFiles)
            {
                DocumentCore dc = DocumentCore.Load(file);

                Console.WriteLine("Adding: {0}...", Path.GetFileName(file));

                // Create import session.
                ImportSession session = new ImportSession(dc, singlePDF, StyleImportingMode.KeepSourceFormatting);

                // Loop through all sections in the source document.
                foreach (Section sourceSection in dc.Sections)
                {
                    // Because we are copying a section from one document to another,
                    // it is required to import the Section into the destination document.
                    // This adjusts any document-specific references to styles, bookmarks, etc.
                    //
                    // Importing a element creates a copy of the original element, but the copy
                    // is ready to be inserted into the destination document.
                    Section importedSection = singlePDF.Import<Section>(sourceSection, true, session);

                    // First section start from new page.
                    if (dc.Sections.IndexOf(sourceSection) == 0)
                        importedSection.PageSetup.SectionStart = SectionStart.NewPage;

                    // Now the new section can be appended to the destination document.
                    singlePDF.Sections.Add(importedSection);
                }
            }

            // Save single PDF to a file.
            singlePDF.Save(singlePDFPath);

            // Open the result for demonstration purposes.
           System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(singlePDFPath) { UseShellExecute = true });
        }
    }
}

Download

Imports System
Imports System.IO
Imports System.Collections.Generic
Imports SautinSoft.Document

Namespace Sample
    Friend Class Sample

        Shared Sub Main(ByVal args() As String)
            MergeMultipleDocuments()
        End Sub
        ''' Get your free 30-day key here:   
        ''' https://sautinsoft.com/start-for-free/
        ''' <summary>
        ''' This sample shows how to merge multiple DOCX, RTF, PDF and Text files.
        ''' </summary>
        ''' <remarks>
        ''' Details: https://sautinsoft.com/products/document/help/net/developer-guide/merge-multiple-files-net-csharp-vb.php
        ''' </remarks>
        Public Shared Sub MergeMultipleDocuments()
            ' Path to our combined document.
            Dim singlePDFPath As String = "Single.pdf"
            Dim workingDir As String = "..\..\..\"

            Dim supportedFiles As New List(Of String)()
            ' Fill the collection 'supportedFiles' by *.docx, *.pdf and *.txt.
            For Each file As String In Directory.GetFiles(workingDir, "*.*")
                Dim ext As String = Path.GetExtension(file).ToLower()

                If ext = ".docx" OrElse ext = ".pdf" OrElse ext = ".txt" Then
                    supportedFiles.Add(file)
                End If
            Next file


            ' Create single pdf.
            Dim singlePDF As New DocumentCore()

            For Each file As String In supportedFiles
                Dim dc As DocumentCore = DocumentCore.Load(file)

                Console.WriteLine("Adding: {0}...", Path.GetFileName(file))

                ' Create import session.
                Dim session As New ImportSession(dc, singlePDF, StyleImportingMode.KeepSourceFormatting)

                ' Loop through all sections in the source document.
                For Each sourceSection As Section In dc.Sections
                    ' Because we are copying a section from one document to another,
                    ' it is required to import the Section into the destination document.
                    ' This adjusts any document-specific references to styles, bookmarks, etc.
                    '
                    ' Importing a element creates a copy of the original element, but the copy
                    ' is ready to be inserted into the destination document.
                    Dim importedSection As Section = singlePDF.Import(Of Section)(sourceSection, True, session)

                    ' First section start from new page.
                    If dc.Sections.IndexOf(sourceSection) = 0 Then
                        importedSection.PageSetup.SectionStart = SectionStart.NewPage
                    End If

                    ' Now the new section can be appended to the destination document.
                    singlePDF.Sections.Add(importedSection)
                Next sourceSection
            Next file

            ' Save single PDF to a file.
            singlePDF.Save(singlePDFPath)

            ' Open the result for demonstration purposes.
            System.Diagnostics.Process.Start(New System.Diagnostics.ProcessStartInfo(singlePDFPath) With {.UseShellExecute = True})
        End Sub
    End Class
End Namespace

Download


If you need a new code example or have a question: email us at support@sautinsoft.com or ask at Online Chat (right-bottom corner of this page) or use the Form below:



Questions and suggestions from you are always welcome!

We are developing .Net components since 2002. We know PDF, DOCX, RTF, HTML, XLSX and Images formats. If you need any assistance with creating, modifying or converting documents in various formats, we can help you. We will write any code example for you absolutely free.