Zum Fußzeileninhalt springen
PRODUKTVERGLEICHE

Wie man PDF-Dateien mit iTextSharp zusammenfügt

Merging PDF documents is a common requirement in various software applications, such as document management systems, report generation tools, and more. In the .NET ecosystem, developers have several libraries at their disposal to manipulate PDF files. iTextSharp and IronPDF are two popular choices for working with PDFs in C# applications. In this article, we will explore how to merge PDFs using iTextSharp and compare it with IronPDF to help you make an informed decision when choosing a library for your PDF manipulation needs.

How to Merge PDF Files Using iTextSharp

Here's a step-by-step guide on how to merge PDFs using iTextSharp:

  1. Create a new Document object and specify a base path for your PDF files.
  2. Open the Document for editing.
  3. Define an array of PDF file names to merge.
  4. For each PDF file in the list, create a PdfReader, add its contents to the PdfCopy object, and then close the PdfReader.
  5. Close the Document, finalizing the merged PDF.

IronPDF

IronPDF Webpage is a .NET library that empowers developers to create, modify, and interact with PDF documents within their C# and .NET applications. It simplifies PDF-related tasks by offering features like PDF generation from scratch, HTML to PDF conversion, PDF manipulation (including adding, removing, and modifying content), interactive form handling, PDF merging and splitting, encryption, and cross-platform compatibility, making it a valuable tool for a wide range of applications requiring PDF document management and generation.

iTextSharp

iTextSharp has been replaced by iText 7, as it has reached its End-of-Life (EOL), with only security fixes in sight. It's highly recommended to use iText 7 or consider transitioning existing ones for new projects. iText 7 offers significant improvements, including HTML to PDF conversion, PDF redaction, SVG support, better language support, debugging tools, data extraction, and more modular functionality. It simplifies PDF document handling and is available under AGPL and Commercial licenses.

Install IronPDF Library

To install the IronPDF NuGet package in your Visual Studio project, you can follow these steps:

  1. Start by opening your project in Visual Studio where you want to use the IronPDF library.
  2. If you're using Visual Studio, go to Tools > NuGet Package Manager > Package Manager Console.
  3. In the Package Manager Console, run the following command to install IronPDF:
Install-Package IronPdf

Visual Studio will download and install the package and its dependencies. You can monitor the progress in the Output window. Once the installation is complete, you can start using IronPDF in your C# code.

**How to Merge PDF Files Using iTextSharp: Figure 1 - The completed installation shown in the built-in terminal in Visual Studio.**

With IronPDF successfully installed, you can now start using it in your project. Include the necessary "using" statements in your code files and begin working with PDFs using IronPDF's functionality.

using IronPdf;
using IronPdf;
Imports IronPdf
$vbLabelText   $csharpLabel

You can now access the features and functionality provided by IronPDF to work with PDF documents in your C# project. Remember to save your project and build it to ensure that the library is properly integrated.

Install iTextSharp PDF Library

To install the iTextSharp PDF library in a C# project, follow these steps:

  1. Open the C# project where you want to use the iTextSharp library in your preferred integrated development environment (IDE), such as Visual Studio.
  2. Go to Tools > NuGet Package Manager > Package Manager Console.
  3. In the Package Manager Console, run the following command:
Install-Package iTextSharp

This command tells NuGet (the package manager for Visual Studio) to download and install the iTextSharp package and its dependencies into your project.

NuGet will download and install the iTextSharp package and any required dependencies. You can monitor the installation progress in the Package Manager Console.

**How to Merge PDF Files Using iTextSharp**: Figure 2 - The completed installation shown in the built-in terminal in Visual Studio.

Once the installation is complete, you'll see a confirmation message in the Package Manager Console indicating that the iTextSharp package has been successfully installed. With iTextSharp successfully installed, you can now start using it in your project. Include the necessary using statements in your code files and begin working with PDFs using iTextSharp's functionality.

Merge PDFs to a Single PDF Document Using IronPDF

IronPDF provides a direct method to merge multiple PDF files into a single PDF. IronPDF offers great flexibility when it comes to merging PDF documents. The following sample code demonstrates the merging of PDFs into a single PDF file:

using IronPdf;
using System.Collections.Generic;

static void Main(string[] args)
{
    string basePath = @"D:\PDFFiles\";
    string[] pdfFiles = { "PdfFile_1.pdf", "PdfFile_2.pdf" };

    // Create a list to hold the PDF documents to be merged
    List<PdfDocument> docList = new List<PdfDocument>();

    // Add each PDF to the list
    foreach (string filename in pdfFiles)
    {
        docList.Add(new PdfDocument(basePath + filename));
    }

    // Merge the PDFs into one document
    var mergedPDF = PdfDocument.Merge(docList);

    // Save the merged PDF to the specified path
    mergedPDF.SaveAs(basePath + "mergePDFbyIronPDF.pdf");
}
using IronPdf;
using System.Collections.Generic;

static void Main(string[] args)
{
    string basePath = @"D:\PDFFiles\";
    string[] pdfFiles = { "PdfFile_1.pdf", "PdfFile_2.pdf" };

    // Create a list to hold the PDF documents to be merged
    List<PdfDocument> docList = new List<PdfDocument>();

    // Add each PDF to the list
    foreach (string filename in pdfFiles)
    {
        docList.Add(new PdfDocument(basePath + filename));
    }

    // Merge the PDFs into one document
    var mergedPDF = PdfDocument.Merge(docList);

    // Save the merged PDF to the specified path
    mergedPDF.SaveAs(basePath + "mergePDFbyIronPDF.pdf");
}
Imports IronPdf
Imports System.Collections.Generic

Shared Sub Main(ByVal args() As String)
	Dim basePath As String = "D:\PDFFiles\"
	Dim pdfFiles() As String = { "PdfFile_1.pdf", "PdfFile_2.pdf" }

	' Create a list to hold the PDF documents to be merged
	Dim docList As New List(Of PdfDocument)()

	' Add each PDF to the list
	For Each filename As String In pdfFiles
		docList.Add(New PdfDocument(basePath & filename))
	Next filename

	' Merge the PDFs into one document
	Dim mergedPDF = PdfDocument.Merge(docList)

	' Save the merged PDF to the specified path
	mergedPDF.SaveAs(basePath & "mergePDFbyIronPDF.pdf")
End Sub
$vbLabelText   $csharpLabel

The above code uses the IronPDF library to merge two PDF files ("PdfFile_1.pdf" and "PdfFile_2.pdf") located in the specified base path ("D:\PDFFiles"). It creates a list of PdfDocument objects, adds the input PDFs to the list, merges them into a single PDF using PdfDocument.Merge, and saves the merged PDF as "mergePDFbyIronPDF.pdf" in the same base path.

The following is the sample PDFs used in this example:

**How to Merge PDF Files Using iTextSharp**: Figure 3 - A simple PDF file, with a title A Simple PDF File and some body text beneath, along with a single-page PDF article.

The following is the merged PDF file:

**How to Merge PDF Files Using iTextSharp**: Figure 4 - The combined PDF, with the simple PDF first and the article second.

Merge Multiple PDF Files using iTextSharp

iTextSharp does not provide a direct method to merge PDF files. However, we can achieve it by opening each input PDF and adding its content to the output document. The following sample code merges PDF files into a single PDF document:

using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;

static void Main(string[] args)
{
    // Create a new Document
    Document doc = new Document();

    string basePath = @"D:\PDFFiles\";

    // Create a PdfCopy instance to copy pages from source PDFs
    PdfCopy copy = new PdfCopy(doc, new FileStream(basePath + "mergePdf.pdf", FileMode.Create));

    // Open the document for writing
    doc.Open();

    string[] pdfFiles = { "PdfFile_1.pdf", "PdfFile_2.pdf" };

    // Loop through all the PDF files to be merged
    foreach (string filename in pdfFiles)
    {
        // Read the content of each PDF
        PdfReader reader = new PdfReader(basePath + filename);

        // Add the document to PdfCopy
        copy.AddDocument(reader);

        // Close the reader
        reader.Close();
    }

    // Close the Document
    doc.Close();
}
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;

static void Main(string[] args)
{
    // Create a new Document
    Document doc = new Document();

    string basePath = @"D:\PDFFiles\";

    // Create a PdfCopy instance to copy pages from source PDFs
    PdfCopy copy = new PdfCopy(doc, new FileStream(basePath + "mergePdf.pdf", FileMode.Create));

    // Open the document for writing
    doc.Open();

    string[] pdfFiles = { "PdfFile_1.pdf", "PdfFile_2.pdf" };

    // Loop through all the PDF files to be merged
    foreach (string filename in pdfFiles)
    {
        // Read the content of each PDF
        PdfReader reader = new PdfReader(basePath + filename);

        // Add the document to PdfCopy
        copy.AddDocument(reader);

        // Close the reader
        reader.Close();
    }

    // Close the Document
    doc.Close();
}
Imports iTextSharp.text
Imports iTextSharp.text.pdf
Imports System.IO

Shared Sub Main(ByVal args() As String)
	' Create a new Document
	Dim doc As New Document()

	Dim basePath As String = "D:\PDFFiles\"

	' Create a PdfCopy instance to copy pages from source PDFs
	Dim copy As New PdfCopy(doc, New FileStream(basePath & "mergePdf.pdf", FileMode.Create))

	' Open the document for writing
	doc.Open()

	Dim pdfFiles() As String = { "PdfFile_1.pdf", "PdfFile_2.pdf" }

	' Loop through all the PDF files to be merged
	For Each filename As String In pdfFiles
		' Read the content of each PDF
		Dim reader As New PdfReader(basePath & filename)

		' Add the document to PdfCopy
		copy.AddDocument(reader)

		' Close the reader
		reader.Close()
	Next filename

	' Close the Document
	doc.Close()
End Sub
$vbLabelText   $csharpLabel

The above code using iTextSharp merges two PDF files ("PdfFile_1.pdf" and "PdfFile_2.pdf") from the specified base path ("D:\PDFFiles") into a single PDF named "mergePdf.pdf." It accomplishes this by opening each input PDF, adding its content to the output document, and then closing the documents. The above code will merge multiple PDFs into one PDF.

We have used two input files as follows:

**How to Merge PDF Files Using iTextSharp**: Figure 5 - The same input PDFs as earlier.

The new file created by our code is as follows:

**How to Merge PDF Files Using iTextSharp**: Figure 6 - The combined PDF, with the simple PDF first and the article second.

Conclusion

In comparison to iTextSharp, IronPDF emerges as the superior choice for merging PDF documents in C# applications. While both libraries are capable, IronPDF offers a more user-friendly interface, modern features like HTML to PDF conversion, clear licensing options, straightforward integration through NuGet, and active development, collectively simplifying the merging process, reducing development time, and ensuring a more reliable solution for PDF-related tasks. Its user-friendly interface, robust feature set, and continuous development make IronPDF the superior solution for merging PDFs in C#.

Hinweis:iText 7 is a registered trademark of its respective owner. This site is not affiliated with, endorsed by, or sponsored by iText 7. All product names, logos, and brands are property of their respective owners. Comparisons are for informational purposes only and reflect publicly available information at the time of writing.

Häufig gestellte Fragen

Wie kann ich PDF-Dateien in C# zusammenführen?

Sie können PDF-Dateien in C# mit IronPDF zusammenführen, indem Sie eine Liste von PdfDocument-Objekten erstellen und die PdfDocument.Merge-Methode verwenden, um sie in ein einziges PDF-Dokument zu kombinieren.

Was sind die Vorteile der Verwendung von IronPDF für die PDF-Bearbeitung?

IronPDF bietet eine benutzerfreundliche Oberfläche, moderne Funktionen wie die HTML-zu-PDF-Konvertierung, interaktive Formulare und plattformübergreifende Kompatibilität, was es zu einem effizienten Werkzeug für die PDF-Manipulation in C#-Anwendungen macht.

Wie installiere ich eine PDF-Bibliothek in Visual Studio für C#-Projekte?

Um IronPDF in einem Visual Studio C#-Projekt zu installieren, verwenden Sie den NuGet-Paketmanager, indem Sie den Befehl 'Install-Package IronPDF' in der Paket-Manager-Konsole ausführen.

Was sind die Unterschiede zwischen iTextSharp und IronPDF beim Zusammenführen von PDFs?

iTextSharp erfordert das manuelle Hinzufügen von Inhalten aus jedem PDF-Dokument, während IronPDF eine einfachere Lösung mit einer direkten Methode zum Zusammenführen von PDFs bietet, wodurch Entwicklungszeit und Komplexität reduziert werden.

Warum sollten Entwickler von iTextSharp zu iText 7 oder IronPDF wechseln?

Entwickler sollten wechseln, weil iTextSharp das Ende seines Lebenszyklus erreicht hat, während iText 7 verbesserte Funktionalitäten bietet. Allerdings bietet IronPDF noch modernere Funktionen und eine leichtere Bedienung, was es zu einer überlegenen Wahl für die PDF-Manipulation macht.

Kann IronPDF mehr als nur das Zusammenführen von PDF-Dateien?

Ja, IronPDF unterstützt eine breite Palette von PDF-Manipulationen, einschließlich der Erstellung von PDFs von Grund auf, der Konvertierung von HTML in PDF, der Änderung von Inhalten, der Handhabung von Formularen und der Anwendung von Verschlüsselung.

Was macht IronPDF zu einer zuverlässigen Wahl für die PDF-Manipulation in C#?

IronPDF wird aktiv entwickelt, bietet moderne Funktionen und verfügt über eine benutzerfreundliche Oberfläche, die PDF-Manipulationsaufgaben vereinfacht, was es zu einer zuverlässigen und effizienten Wahl für Entwickler macht.

Wie verbessert IronPDF den Prozess des Zusammenführens von PDFs im Vergleich zu älteren Bibliotheken?

IronPDF verbessert den Zusammenführungsprozess, indem es direkte Methoden zur Kombination von PDF-Dateien bietet, die Integration in C#-Projekte vereinfacht und die Gesamtentwicklungszeit reduziert.

Welche Überlegungen sollten Entwickler bei der Auswahl einer PDF-Bibliothek für C# im Auge behalten?

Entwickler sollten Faktoren wie Benutzerfreundlichkeit, Funktionsumfang, Lizenzierungsoptionen, Kompatibilität und aktive Entwicklungsunterstützung berücksichtigen, wenn sie eine PDF-Bibliothek für C#-Projekte auswählen. IronPDF glänzt in diesen Bereichen und ist daher die bevorzugte Wahl.

Curtis Chau
Technischer Autor

Curtis Chau hat einen Bachelor-Abschluss in Informatik von der Carleton University und ist spezialisiert auf Frontend-Entwicklung mit Expertise in Node.js, TypeScript, JavaScript und React. Leidenschaftlich widmet er sich der Erstellung intuitiver und ästhetisch ansprechender Benutzerschnittstellen und arbeitet gerne mit modernen Frameworks sowie der Erstellung gut strukturierter, optisch ansprechender ...

Weiterlesen