跳過到頁腳內容
產品比較

在C#中拆分PDF的比較iTextSharp與IronPDF之間

PDF(便携式文档格式)文件被广泛用于共享和演示文档,有时您可能需要将一个PDF拆分成多个文件。 无论您是想提取特定页面,将大型文档分成小部分,还是为每章创建单独的文件,拆分PDF在各种场景中都是一个有价值的任务。

在本文中,我们将学习如何使用C#拆分PDF。 C#是一种多功能且强大的语言,已经有几个库可以使操作PDF相对简单。 我们将探索使用C#拆分PDF的以下两个库。

  1. iTextSharp
  2. IronPDF

如何使用iTextSharp在C#中拆分PDF

  1. 首先,安装iText7库。
  2. 从输入的PDF文件创建一个PdfReader。
  3. 使用PdfDocument处理PDF内容。
  4. 计算每个拆分文件的页数。
  5. 设置初始页面范围值。
  6. 使用循环处理每个拆分文件。
  7. 为当前拆分文件创建新的PdfDocument。
  8. 将页面从原始文档复制到新文档。
  9. 更新下一次迭代的页面范围值。
  10. 保存已完成的输出PDF。
  11. 重复直到所有文件创建完成。
  12. 对指定的拆分文件数量继续该过程。

IronPDF

C#中iTextSharp和IronPDF拆分PDF的比较:图1 - IronPDF网页

IronPDF是一个功能强大的C#库,专为处理PDF文件而设计。 It provides features for creating, modifying, and extracting content from PDF documents. 开发人员可以从头生成PDF,编辑现有PDF,并合并或拆分它们。 此外,IronPDF在将HTML内容转换为PDF格式方面表现出色,这使得它在生成报告或文档时非常有用。 通过支持数字签名、安全功能和高质量输出,IronPDF简化了.NET应用程序中的PDF相关任务。

iTextSharp

C#中iTextSharp和IronPDF拆分PDF的比较:图2 - iTextSharp网页

iTextSharp (iText 7)是用于在.NET框架中处理PDF文件的广泛使用的库。 它为程序化地创建、修改和提取PDF文档内容提供了强大的功能。 开发人员可以使用iTextSharp向PDF添加文本、图像、表格和其他图形元素。 此外,它支持文档组装、数字签名,以及符合归档和可访问性标准的功能。 最初是一个Java库,iTextSharp被移植到.NET,并拥有活跃的开发者和用户社区。

安装IronPDF库

要使用Visual Studio中的包管理器控制台安装IronPDF NuGet包,请按照以下步骤操作:

  1. 在Visual Studio中,进入工具 -> NuGet包管理器 -> 包管理器控制台。
  2. 使用以下命令安装IronPDF NuGet包:

    Install-Package IronPdf

这将下载并安装IronPDF包及其依赖项到您的项目中。 安装完成后,您可以开始在您的C#项目中使用IronPDF进行PDF相关任务。

或者,您可以使用Visual Studio中的NuGet包管理器安装IronPDF,或直接将包添加到项目文件中。另一个选项是从官方网站下载包并手动添加到您的项目中。 每种方法都为将IronPDF集成到您的C#项目中提供了一种简单的方法,以实现PDF相关功能。

安装iTextSharp库

要在Visual Studio中使用包管理器控制台安装iTextSharp,您可以按照以下步骤操作:

  1. 在Visual Studio中,进入工具 -> NuGet包管理器 -> 包管理器控制台。
  2. 使用以下命令安装iTextSharp NuGet包:

    Install-Package itext7
    Install-Package itext7
    SHELL

这将下载并安装iTextSharp包及其依赖项到您的项目中。 安装完成后,您可以开始在您的C#项目中使用iTextSharp处理PDF。

使用IronPDF在C#中拆分PDF文档

我们可以使用IronPDF将一个PDF文件拆分成多个PDF文件。 它提供了一个简单的方法来实现这一点。 以下代码将以源PDF文件为输入并将其拆分成多个PDF文件。

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

代碼說明

此代码的目的是使用IronPDF库将给定的PDF文件拆分成多个较小的PDF文件。 SplitPdfUsingIronPDF方法被定义以实现此功能。

方法参数

  1. inputPdfPath: 一个表示输入PDF文件路径的字符串(如“input.pdf”)。
  2. outputFolder: 一个表示拆分PDF文件将被保存到的输出文件夹的字符串(如“output_split”)。
  3. numberOfSplitFiles: 一个表示原始PDF将被拆分成多少个较小文件的整数。

拆分过程

SplitPdfUsingIronPDF方法内:

  1. 一个名为sourceFilePdfDocument对象通过从指定的inputPdfPath加载PDF来创建。
  2. 初始化两个整数变量firstPagelastPage。 这些表示用于拆分的页面范围。
  3. totalPageInOneFile通过将源PDF的总页数除以指定的numberOfSplitFiles来计算。
  4. 一个循环从1迭代到numberOfSplitFiles
  5. 创建一个新的名为newSplitPDFPdfDocument对象。
  6. firstPagelastPage(含)的页面从sourceFile复制到newSplitPDF
  7. 生成的较小PDF被保存,文件名如“SplitPDF_IronPDF_1.pdf”(对于第一个拆分)在指定的输出文件夹中。
  8. 为下次迭代更新firstPagelastPage值。

注意

您应替换“input.pdf”为实际的输入PDF文件路径。确保IronPDF库已正确安装并在您的项目中引用。

输出文件创建为:

C#中iTextSharp和IronPDF拆分PDF的比较:图3 - 创建的输出文件

使用iTextSharp在C#中拆分PDF

现在,我们将使用iTextSharp将我们的PDF文档拆分为多个PDF文件。 以下代码将以源文件为输入并将该PDF文档拆分成多个较小的文件。

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

代码解释

此代码演示如何使用iTextSharp将大型PDF文件拆分成较小块。每个较小的PDF文档将包含原始文档的一部分。

使用iTextSharp拆分PDF

  1. 主要功能封装在SplitPdfUsingiTextSharp方法中。
  2. 上述方法接受三个参数:inputPdfPathoutputFolder,和numberOfSplitFiles

使用PdfReader和PdfDocument

SplitPdfUsingiTextSharp方法内:

  1. 一个名为readerPdfReader对象通过从指定的inputPdfPath加载PDF创建。
  2. 一个名为docPdfDocument对象使用reader被初始化。
  3. 源PDF中的总页数除以numberOfSplitFiles以确定每个较小PDF应包含多少页。

拆分过程

一个循环从1迭代到numberOfSplitFiles:

  1. 一个新的较小PDF文件被创建,文件名如“SplitPDF_iTextSharp_1.pdf”(对于第一个拆分)在指定的输出文件夹中。
  2. 在这个新的PDF文档(pdfDocument)中,页面从原始doc复制过来:
  3. firstPagelastPage(含)进行复制。
  4. 较小的PDF被保存。
  5. 为下次迭代更新firstPagelastPage值。

注意

确保iTextSharp库已正确安装并在您的项目中引用。 将“input.pdf”替换为您输入PDF文件的实际路径。

C#中iTextSharp和IronPDF拆分PDF的比较:图4 - 创建的输出文件

比較

要比较使用iTextSharp和IronPDF的两种拆分方法,让我们根据几个因素评估它们:

  1. 易用性:
    • iTextSharp: iTextSharp方法涉及创建PdfReader、PdfDocument和PdfWriter。 它计算页面范围并将页面复制到新文档。 此方法需要理解iTextSharp API。
    • IronPDF: IronPDF方法涉及从源文件创建一个PdfDocument,复制页面并将其保存到新文件。它有一个更简单的API。
  2. 代码可读性:
    • iTextSharp: 代码涉及更多步骤,使其稍微长一些并可能更复杂以阅读。
    • IronPDF: 代码由于步骤更少和方法调用更少且更易阅读。
  3. 性能:
    • iTextSharp: 性能可能受制于重复创建和销毁PdfDocument实例。
    • IronPDF: 方法涉及的步骤更少,因高效的页面复制而提供更好的性能。
  4. 内存使用:
    • iTextSharp: 创建多个PdfDocument实例会消耗更多内存。
    • IronPDF: 该方法因其简化的方法而更具内存效率。

結論

总之,iTextSharp和IronPDF都为C#中的PDF文件拆分提供了强大的解决方案,各自有其优点。 IronPDF因其简易性、可读性以及由于更直接的方法而可能有更好的性能而脱颖而出。

寻求在多功能性和易用性之间找到平衡的开发人员可能会发现IronPDF是一个有吸引力的选择。此外,IronPDF提供免费试用。 最终,iTextSharp和IronPDF之间的选择取决于个人项目要求和偏好的开发风格。

請注意iTextSharp 是其各自所有者的註冊商標。 本網站未被 iTextSharp 授權、贊助或認可。所有產品名稱、商標和品牌均為其各自所有者的財產。 比較僅供信息參考,並反映撰寫時公開可用的信息。

常見問題解答

如何在 C# 中拆分 PDF 並保持原始格式?

您可以使用 IronPDF 在 C# 中拆分 PDF 同時保留其格式。IronPDF 提供了一個簡單的 API,允許您加載 PDF 並指定要拆分的頁面範圍,確保原始格式在生成的 PDF 中保持不變。

iTextSharp 和 IronPDF 在 C# 中用於拆分 PDF 的主要區別是什麼?

主要差異在於易用性和性能。IronPDF 提供更簡單的 API,步驟更少,使拆分 PDF 更容易且不丟失格式。另一方面,iTextSharp 需要創建 PdfReaderPdfDocumentPdfWriter 等多個實例,這可能更複雜。

我可以使用 C# 從 PDF 中提取特定頁面嗎?

是的,使用 IronPDF,您可以輕鬆從 PDF 中提取特定頁面。通過加載 PDF 並指定所需的頁碼,IronPDF 允許您提取並將這些頁面保存為新的 PDF 文件。

IronPDF 如何改善與其他 PDF 庫相比的代碼可讀性?

IronPDF 通過提供清晰簡潔的 API 改善代碼可讀性,減少對多個類和對象的需求。這簡化了拆分之類的 PDF 操作任務所需的代碼,導致代碼更清晰且更易於維護。

在購買庫之前,是否可以在 C# 中測試 PDF 分割功能?

是的,IronPDF 提供免費試用,允許開發人員測試其 PDF 分割功能和其他功能。這一試用期使您能夠在做出購買決定之前評估其功能和性能。

選擇用於拆分文檔的 PDF 庫時應考慮哪些因素?

選擇 PDF 庫時,應考慮易用性、API 簡單性、性能以及維護原始文件格式的能力等因素。IronPDF 由於其易於使用的 API 和高效性能而常被優先選擇。

如何在 Visual Studio C# 項目中安裝 IronPDF?

要在 Visual Studio C# 項目中安裝 IronPDF,請使用 NuGet 包管理器控制台,輸入命令 Install-Package IronPdf。您還可以通過 NuGet 包管理器 UI 添加或從 IronPDF 的官方網站下載。

拆分 PDF 會影響其質量或格式嗎?

使用 IronPDF 拆分 PDF 可確保保持原始文件的質量和格式。IronPDF 的高效處理保持了原始內容的完整性。

Curtis Chau
技術作家

Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。