Zum Fußzeileninhalt springen
PRODUKTVERGLEICHE

Ein Vergleich des Aufteilens von PDF in C# zwischen iTextSharp und IronPDF

PDF (Portable Document Format) files are widely used for sharing and presenting documents, and there are times when you may need to split a PDF into multiple files. Whether you want to extract specific pages, divide a large document into smaller sections, or create individual files for each chapter, splitting PDFs can be a valuable task in various scenarios.

In this article, we'll learn how to split PDFs using C#. C# is a versatile and powerful language, and there are several libraries available that make it relatively straightforward to manipulate PDFs. We will explore the following two libraries for splitting PDFs in C#.

  1. iTextSharp
  2. IronPDF

How to Split PDF in C# Using iTextSharp

  1. First, install the iText7 library.
  2. Create a PdfReader from the input PDF file.
  3. Use a PdfDocument to work with the PDF content.
  4. Calculate the number of pages for each split file.
  5. Set initial page range values.
  6. Use a loop to process each split file.
  7. Create a new PdfDocument for the current split file.
  8. Copy pages from the original document to the new one.
  9. Update page range values for the next iteration.
  10. Save the completed output PDF.
  11. Repeat until all files are created.
  12. Continue the process for the specified number of split files.

IronPDF

A Comparison of Splitting PDF in C# Between iTextSharp and IronPDF: Figure 1 - IronPDF webpage

IronPDF is a powerful C# library designed for working with PDF files. It provides features for creating, modifying, and extracting content from PDF documents. Developers can generate PDFs from scratch, edit existing PDFs, and merge or split them. Additionally, IronPDF excels at converting HTML content to PDF format, making it useful for generating reports or documentation. With support for digital signatures, security features, and high-quality output, IronPDF simplifies PDF-related tasks in .NET applications.

iTextSharp

A Comparison of Splitting PDF in C# Between iTextSharp and IronPDF: Figure 2 - iTextSharp webpage

iTextSharp (iText 7) is a widely used library for working with PDF files in the .NET framework. It provides powerful features for creating, modifying, and extracting content from PDF documents programmatically. Developers can use iTextSharp to add text, images, tables, and other graphical elements to PDFs. Additionally, it supports document assembly, digital signatures, and compliance with archival and accessibility standards. Originally a Java library, iTextSharp was ported to .NET and has an active community of developers and users.

Installing the IronPDF Library

To install the IronPDF NuGet package using Package Manager Console in Visual Studio, follow these steps:

  1. In Visual Studio, go to Tools -> NuGet Package Manager -> Package Manager Console.
  2. Use the following command to install the IronPDF NuGet package:

    Install-Package IronPdf

This will download and install the IronPDF package along with its dependencies into your project. Once the installation is complete, you can start using IronPDF in your C# project for PDF-related tasks.

Alternatively, you can install IronPDF using the NuGet Package Manager in Visual Studio, or add the package directly to your project file. Another option is downloading the package from the official website and manually adding it to your project. Each method provides a straightforward way to integrate IronPDF into your C# project for PDF-related functionalities.

Installing the iTextSharp Library

To install iTextSharp using Package Manager Console in Visual Studio, you can follow these steps:

  1. In Visual Studio, go to Tools -> NuGet Package Manager -> Package Manager Console.
  2. Use the following command to install the iTextSharp NuGet package:

    Install-Package itext7
    Install-Package itext7
    SHELL

This will download and install the iTextSharp package along with its dependencies into your project. Once the installation is complete, you can start using iTextSharp in your C# project for working with PDFs.

Split PDF Documents in C# Using IronPDF

We can split a PDF file into multiple PDF files using IronPDF. It provides a simple way to achieve this. The following code will take the source PDF file as input and split it into multiple PDF files.

using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        string file = "input.pdf";
        // The folder to save the split PDFs
        string outputFolder = "output_split";
        int numberOfSplitFiles = 3; // Specify how many parts you want to split the PDF into
        // Call the SplitPdf method to split the PDF
        SplitPdfUsingIronPDF(file, outputFolder, numberOfSplitFiles);
    }

    static void SplitPdfUsingIronPDF(string inputPdfPath, string outputFolder, int numberOfSplitFiles)
    {
        // Load the input PDF
        PdfDocument sourceFile = PdfDocument.FromFile(inputPdfPath);

        // Initialize page range values
        int firstPage = 1;
        int lastPage = 2;
        int totalPageInOneFile = sourceFile.PageCount / numberOfSplitFiles;

        for (int i = 1; i <= numberOfSplitFiles; i++)
        {
            // Copy multiple pages into a new document
            PdfDocument newSplitPDF = sourceFile.CopyPages(firstPage, lastPage);

            // Generate the output file path
            string name = $@"{outputFolder}\SplitPDF_IronPDF_{i}.pdf";

            // Save the new split PDF
            newSplitPDF.SaveAs(name);

            // Update page range values for the next iteration
            firstPage = lastPage + 1;
            lastPage += totalPageInOneFile;
        }
    }
}
using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        string file = "input.pdf";
        // The folder to save the split PDFs
        string outputFolder = "output_split";
        int numberOfSplitFiles = 3; // Specify how many parts you want to split the PDF into
        // Call the SplitPdf method to split the PDF
        SplitPdfUsingIronPDF(file, outputFolder, numberOfSplitFiles);
    }

    static void SplitPdfUsingIronPDF(string inputPdfPath, string outputFolder, int numberOfSplitFiles)
    {
        // Load the input PDF
        PdfDocument sourceFile = PdfDocument.FromFile(inputPdfPath);

        // Initialize page range values
        int firstPage = 1;
        int lastPage = 2;
        int totalPageInOneFile = sourceFile.PageCount / numberOfSplitFiles;

        for (int i = 1; i <= numberOfSplitFiles; i++)
        {
            // Copy multiple pages into a new document
            PdfDocument newSplitPDF = sourceFile.CopyPages(firstPage, lastPage);

            // Generate the output file path
            string name = $@"{outputFolder}\SplitPDF_IronPDF_{i}.pdf";

            // Save the new split PDF
            newSplitPDF.SaveAs(name);

            // Update page range values for the next iteration
            firstPage = lastPage + 1;
            lastPage += totalPageInOneFile;
        }
    }
}
Imports IronPdf

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim file As String = "input.pdf"
		' The folder to save the split PDFs
		Dim outputFolder As String = "output_split"
		Dim numberOfSplitFiles As Integer = 3 ' Specify how many parts you want to split the PDF into
		' Call the SplitPdf method to split the PDF
		SplitPdfUsingIronPDF(file, outputFolder, numberOfSplitFiles)
	End Sub

	Private Shared Sub SplitPdfUsingIronPDF(ByVal inputPdfPath As String, ByVal outputFolder As String, ByVal numberOfSplitFiles As Integer)
		' Load the input PDF
		Dim sourceFile As PdfDocument = PdfDocument.FromFile(inputPdfPath)

		' Initialize page range values
		Dim firstPage As Integer = 1
		Dim lastPage As Integer = 2
'INSTANT VB WARNING: Instant VB cannot determine whether both operands of this division are integer types - if they are then you should use the VB integer division operator:
		Dim totalPageInOneFile As Integer = sourceFile.PageCount / numberOfSplitFiles

		For i As Integer = 1 To numberOfSplitFiles
			' Copy multiple pages into a new document
			Dim newSplitPDF As PdfDocument = sourceFile.CopyPages(firstPage, lastPage)

			' Generate the output file path
			Dim name As String = $"{outputFolder}\SplitPDF_IronPDF_{i}.pdf"

			' Save the new split PDF
			newSplitPDF.SaveAs(name)

			' Update page range values for the next iteration
			firstPage = lastPage + 1
			lastPage += totalPageInOneFile
		Next i
	End Sub
End Class
$vbLabelText   $csharpLabel

Code Explanation

The purpose of this code is to split a given PDF file into multiple smaller PDF files using the IronPDF library. The SplitPdfUsingIronPDF method is defined to achieve this functionality.

Method Parameters

  1. inputPdfPath: A string representing the path to the input PDF file (e.g., "input.pdf").
  2. outputFolder: A string representing the output folder where the split PDF files will be saved (e.g., "output_split").
  3. numberOfSplitFiles: An integer indicating how many smaller PDF files the original PDF will be split into.

Splitting Process

Inside the SplitPdfUsingIronPDF method:

  1. A PdfDocument object named sourceFile is created by loading the PDF from the specified inputPdfPath.
  2. Two integer variables, firstPage and lastPage, are initialized. These represent the page range for splitting.
  3. totalPageInOneFile is calculated by dividing the total page count of the source PDF by the specified numberOfSplitFiles.
  4. A loop iterates from 1 to numberOfSplitFiles:
  5. A new PdfDocument object named newSplitPDF is created.
  6. Pages from firstPage to lastPage (inclusive) are copied from the sourceFile to newSplitPDF.
  7. The resulting smaller PDF is saved with a filename like "SplitPDF_IronPDF_1.pdf" (for the first split) in the specified output folder.
  8. The firstPage and lastPage values are updated for the next iteration.

Note

You should replace "input.pdf" with the actual path to your input PDF file. Ensure that the IronPDF library is properly installed and referenced in your project.

The output files are created as:

A Comparison of Splitting PDF in C# Between iTextSharp and IronPDF: Figure 3 - Created output files

Split PDFs in C# Using iTextSharp

Now, we will use iTextSharp to split our PDF document into multiple PDF files. The following code will take the source file as input and split that PDF document into multiple smaller files.

using System;
using iText.Kernel.Pdf;

class Program
{
    static void Main(string[] args)
    {
        string inputPath = "input.pdf";
        // Output PDF files path (prefix for the generated files)
        string outputPath = "output_split";
        int numberOfSplitFiles = 3; // Specify how many parts you want to split the PDF into
        // Call the SplitPdf method to split the PDF
        SplitPdfUsingiTextSharp(inputPath, outputPath, numberOfSplitFiles);
    }

    static void SplitPdfUsingiTextSharp(string inputPdfPath, string outputFolder, int numberOfSplitFiles)
    {
        using (PdfReader reader = new PdfReader(inputPdfPath))
        {
            using (PdfDocument doc = new PdfDocument(reader))
            {
                // Calculate the number of pages for each split file
                int totalPageInOneFile = doc.GetNumberOfPages() / numberOfSplitFiles;
                int firstPage = 1;
                int lastPage = totalPageInOneFile;

                for (int i = 1; i <= numberOfSplitFiles; i++)
                {
                    // Generate the output file path
                    string filename = $@"{outputFolder}\SplitPDF_iTextSharp_{i}.pdf";

                    // Create a new document and attach a writer for the specified output file
                    using (PdfDocument pdfDocument = new PdfDocument(new PdfWriter(filename)))
                    {
                        // Copy pages from the original document to the new document
                        doc.CopyPagesTo(firstPage, lastPage, pdfDocument);
                    }

                    // Update page range values for the next iteration
                    firstPage = lastPage + 1;
                    lastPage += totalPageInOneFile;
                }
            }
        }
    }
}
using System;
using iText.Kernel.Pdf;

class Program
{
    static void Main(string[] args)
    {
        string inputPath = "input.pdf";
        // Output PDF files path (prefix for the generated files)
        string outputPath = "output_split";
        int numberOfSplitFiles = 3; // Specify how many parts you want to split the PDF into
        // Call the SplitPdf method to split the PDF
        SplitPdfUsingiTextSharp(inputPath, outputPath, numberOfSplitFiles);
    }

    static void SplitPdfUsingiTextSharp(string inputPdfPath, string outputFolder, int numberOfSplitFiles)
    {
        using (PdfReader reader = new PdfReader(inputPdfPath))
        {
            using (PdfDocument doc = new PdfDocument(reader))
            {
                // Calculate the number of pages for each split file
                int totalPageInOneFile = doc.GetNumberOfPages() / numberOfSplitFiles;
                int firstPage = 1;
                int lastPage = totalPageInOneFile;

                for (int i = 1; i <= numberOfSplitFiles; i++)
                {
                    // Generate the output file path
                    string filename = $@"{outputFolder}\SplitPDF_iTextSharp_{i}.pdf";

                    // Create a new document and attach a writer for the specified output file
                    using (PdfDocument pdfDocument = new PdfDocument(new PdfWriter(filename)))
                    {
                        // Copy pages from the original document to the new document
                        doc.CopyPagesTo(firstPage, lastPage, pdfDocument);
                    }

                    // Update page range values for the next iteration
                    firstPage = lastPage + 1;
                    lastPage += totalPageInOneFile;
                }
            }
        }
    }
}
Imports System
Imports iText.Kernel.Pdf

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim inputPath As String = "input.pdf"
		' Output PDF files path (prefix for the generated files)
		Dim outputPath As String = "output_split"
		Dim numberOfSplitFiles As Integer = 3 ' Specify how many parts you want to split the PDF into
		' Call the SplitPdf method to split the PDF
		SplitPdfUsingiTextSharp(inputPath, outputPath, numberOfSplitFiles)
	End Sub

	Private Shared Sub SplitPdfUsingiTextSharp(ByVal inputPdfPath As String, ByVal outputFolder As String, ByVal numberOfSplitFiles As Integer)
		Using reader As New PdfReader(inputPdfPath)
			Using doc As New PdfDocument(reader)
				' Calculate the number of pages for each split file
'INSTANT VB WARNING: Instant VB cannot determine whether both operands of this division are integer types - if they are then you should use the VB integer division operator:
				Dim totalPageInOneFile As Integer = doc.GetNumberOfPages() / numberOfSplitFiles
				Dim firstPage As Integer = 1
				Dim lastPage As Integer = totalPageInOneFile

				For i As Integer = 1 To numberOfSplitFiles
					' Generate the output file path
					Dim filename As String = $"{outputFolder}\SplitPDF_iTextSharp_{i}.pdf"

					' Create a new document and attach a writer for the specified output file
					Using pdfDocument As New PdfDocument(New PdfWriter(filename))
						' Copy pages from the original document to the new document
						doc.CopyPagesTo(firstPage, lastPage, pdfDocument)
					End Using

					' Update page range values for the next iteration
					firstPage = lastPage + 1
					lastPage += totalPageInOneFile
				Next i
			End Using
		End Using
	End Sub
End Class
$vbLabelText   $csharpLabel

Code Explanation

This code demonstrates how to split a large PDF file into smaller chunks using iTextSharp. Each smaller PDF document will contain a portion of the original document.

Splitting PDF Using iTextSharp

  1. The main functionality is encapsulated in the SplitPdfUsingiTextSharp method.
  2. The above method takes three parameters: inputPdfPath, outputFolder, and numberOfSplitFiles.

Using PdfReader and PdfDocument

Inside the SplitPdfUsingiTextSharp method:

  1. A PdfReader object named reader is created by loading the PDF from the specified inputPdfPath.
  2. A PdfDocument object named doc is initialized using the reader.
  3. The total number of pages in the source PDF is divided by numberOfSplitFiles to determine how many pages each smaller PDF should contain.

Splitting Process

A loop iterates from 1 to numberOfSplitFiles:

  1. A new smaller PDF file is created with a filename like "SplitPDF_iTextSharp_1.pdf" (for the first split) in the specified output folder.
  2. Inside this new PDF document (pdfDocument), pages are copied from the original doc:
  3. firstPage to lastPage (inclusive) are copied.
  4. The smaller PDF is saved.
  5. The firstPage and lastPage values are updated for the next iteration.

Note

Ensure that the iTextSharp library is properly installed and referenced in your project. Replace "input.pdf" with the actual path to your input PDF file.

A Comparison of Splitting PDF in C# Between iTextSharp and IronPDF: Figure 4 - Created output files

Comparison

To compare the two split methods using iTextSharp and IronPDF, let's evaluate them based on several factors:

  1. Ease of Use:
    • iTextSharp: The iTextSharp method involves creating a PdfReader, PdfDocument, and PdfWriter. It calculates page ranges and copies pages to a new document. This approach requires understanding the iTextSharp API.
    • IronPDF: The IronPDF method involves creating a PdfDocument from the source file, copying pages, and saving them to a new file. It has a more straightforward API.
  2. Code Readability:
    • iTextSharp: The code involves more steps, making it slightly longer and potentially more complex to read.
    • IronPDF: The code is concise and more readable due to fewer steps and method calls.
  3. Performance:
    • iTextSharp: Performance may be affected by the repeated creation and disposal of PdfDocument instances.
    • IronPDF: The method involves fewer steps and offers better performance due to efficient page copying.
  4. Memory Usage:
    • iTextSharp: Creating multiple PdfDocument instances will consume more memory.
    • IronPDF: The method is more memory-efficient due to its simplified approach.

Conclusion

In conclusion, both iTextSharp and IronPDF offer robust solutions for splitting PDF files in C#, each with its own set of advantages. IronPDF stands out for its simplicity, readability, and potentially better performance due to a more straightforward approach.

Developers seeking a balance between versatility and ease of use may find IronPDF to be a compelling choice. Additionally, IronPDF offers a free trial. Ultimately, the selection between iTextSharp and IronPDF depends on individual project requirements and the preferred development style.

Hinweis:iTextSharp is a registered trademark of its respective owner. This site is not affiliated with, endorsed by, or sponsored by iTextSharp. 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 ein PDF in C# aufteilen, während das ursprüngliche Format beibehalten wird?

Sie können IronPDF verwenden, um ein PDF in C# aufzuteilen, während das Format erhalten bleibt. IronPDF bietet eine einfache API, mit der Sie ein PDF laden und die Seitenbereiche zum Aufteilen angeben können, wobei das ursprüngliche Format in den resultierenden PDFs beibehalten wird.

Was sind die Hauptunterschiede zwischen iTextSharp und IronPDF für das Aufteilen von PDFs in C#?

Die Hauptunterschiede liegen in der Benutzerfreundlichkeit und der Leistung. IronPDF bietet eine einfachere API mit weniger Schritten, was das Aufteilen von PDFs erleichtert, ohne die Formatierung zu verlieren. Auf der anderen Seite erfordert iTextSharp die Erstellung mehrerer Instanzen wie PdfReader, PdfDocument und PdfWriter, was komplizierter sein kann.

Kann ich bestimmte Seiten aus einem PDF mit C# extrahieren?

Ja, mit IronPDF können Sie einfach bestimmte Seiten aus einem PDF in C# extrahieren. Durch Laden des PDFs und Festlegen der gewünschten Seitenzahlen können Sie mit IronPDF diese Seiten extrahieren und als neues PDF-Dokument speichern.

Wie verbessert IronPDF die Lesbarkeit des Codes im Vergleich zu anderen PDF-Bibliotheken?

IronPDF verbessert die Lesbarkeit des Codes durch eine klare und prägnante API, die die Notwendigkeit für mehrere Klassen und Objekte reduziert. Dies vereinfacht den Code, der für Aufgaben zur PDF-Manipulation wie das Aufteilen erforderlich ist, und führt zu einem übersichtlicheren und besser wartbaren Code.

Ist es möglich, die Aufteilungsfunktionalität eines PDFs in C# zu testen, bevor man eine Bibliothek kauft?

Ja, IronPDF bietet eine kostenlose Testversion an, die Entwicklern erlaubt, seine Funktionalitäten zur PDF-Aufteilung und andere Merkmale zu testen. Diese Testphase ermöglicht es Ihnen, seine Fähigkeiten und Leistung zu bewerten, bevor Sie sich für einen Kauf entscheiden.

Welche Faktoren sollten bei der Auswahl einer PDF-Bibliothek zum Aufteilen von Dokumenten berücksichtigt werden?

Bei der Auswahl einer PDF-Bibliothek sollten Faktoren wie Benutzerfreundlichkeit, API-Einfachheit, Leistung und die Fähigkeit, das ursprünglich Format des Dokuments beizubehalten, berücksichtigt werden. IronPDF wird oft aufgrund seiner benutzerfreundlichen API und effizienten Leistung bevorzugt.

Wie kann ich IronPDF in ein Visual Studio C#-Projekt installieren?

Um IronPDF in einem Visual Studio C#-Projekt zu installieren, verwenden Sie die NuGet Package Manager-Konsole mit dem Befehl Install-Package IronPdf. Sie können es auch über die NuGet Package Manager-Oberfläche hinzufügen oder von der offiziellen IronPDF-Website herunterladen.

Beeinflusst das Aufteilen eines PDFs Qualität oder Formatierung?

Das Aufteilen eines PDFs mit IronPDF stellt sicher, dass die Qualität und Formatierung des Originaldokuments erhalten bleibt. IronPDFs effiziente Verarbeitung bewahrt die Integrität des Originalinhalts.

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