Как объединить несколько файлов в один документ с помощью C# и .NET

  1. Добавьте SautinSoft.Document из Nuget.
  2. Создайте пустой отдельный документ.
  3. Загрузите и импортируйте содержимое из каждого документа.
  4. Сохраните отдельный документ.

Здесь мы покажем Вам, как объединить: PDF, DOCX, Txt в один PDF файл.

Несколько шагов:

  1. Обратите внимание, что Вы импортируете пространство имен SautinSoft.Document.
    using SautinSoft.Document;
  2. Прежде всего, Вы должны указать, где взять файлы для преобразования и формат этих файлов (*.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. Например: Нам нужно объединить 1.txt, 2.docx, 3.pdf
  4. Следующим шагом является объединение ВСЕХ найденных файлов в один документ.
    Поскольку мы копируем раздел из одного документа в другой, требуется импортировать раздел в документ назначения.
    Это позволяет настроить любые ссылки на стили, закладки и так далее, относящиеся к конкретному документу.
    
                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. Мы объединили все файлы в один документ. Теперь сохраните его в формате PDF.
    Кстати, Вы можете сохранить эти файлы в формате DOCX, RTF, Text.
    
                // Save single PDF to a file.            
                singlePDF.Save(singlePDFPath);
    
  6. Скачать полученный PDF-файл: Single.pdf

Полный код

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


Если вам нужен пример кода или у вас есть вопрос: напишите нам по адресу [email protected] или спросите в онлайн-чате (правый нижний угол этой страницы) или используйте форму ниже:



Вопросы и предложения всегда приветствуются!

Мы разрабатываем компоненты .Net с 2002 года. Мы знаем форматы PDF, DOCX, RTF, HTML, XLSX и Images. Если вам нужна помощь в создании, изменении или преобразовании документов в различных форматах, мы можем вам помочь. Мы напишем для вас любой пример кода абсолютно бесплатно.