跳至页脚内容
产品比较

在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中使用Package Manager Console安装IronPDF NuGet包,请按照以下步骤操作:

  1. 在Visual Studio中,依次转到工具 -> NuGet包管理器 -> Package Manager Console。
  2. 使用以下命令来安装IronPDF NuGet包:

    Install-Package IronPdf

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

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

安装iTextSharp库

要在Visual Studio中使用Package Manager Console安装iTextSharp,可以按照以下步骤进行:

  1. 在Visual Studio中,依次转到工具 -> NuGet包管理器 -> Package Manager Console。
  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将被拆分成多少个较小的PDF文件。

拆分过程

SplitPdfUsingIronPDF方法内:

  1. 通过加载指定的inputPdfPath处的PDF,创建一个名为sourceFilePdfDocument对象。
  2. 初始化两个整数变量firstPagelastPage。 这代表了拆分的页范围。
  3. totalPageInOneFile通过将源PDF的总页数除以指定的numberOfSplitFiles来计算。
  4. 循环从1迭代到numberOfSplitFiles
  5. 创建一个名为newSplitPDF的新PdfDocument对象。
  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. 上述方法接受三个参数:inputPdfPathoutputFoldernumberOfSplitFiles

使用PdfReader和PdfDocument

SplitPdfUsingiTextSharp方法内部:

  1. 通过加载指定的inputPdfPath处的PDF,创建一个名为readerPdfReader对象。
  2. 使用reader初始化一个名为docPdfDocument对象。
  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之间的选择取决于个人项目需求和偏好的开发风格。

{i:(iTextSharp 是其各自所有者的注册商标。 本网站与 iTextSharp 无关,也未得到 iTextSharp 的支持或赞助。所有产品名称、徽标和品牌均为其各自所有者的财产。 比较仅供参考,反映的是撰写时的公开信息。]

常见问题解答

如何在保持原始格式的情况下,用 C# 分割 PDF?

您可以使用 IronPDF 在 C# 中分割 PDF,同时保留其格式。IronPDF 提供了一个简单的 API,允许您加载 PDF 并指定要分割的页面范围,确保原始格式在生成的 PDF 中保持不变。

在 C# 中分割 PDF 时,iTextSharp 和 IronPDF 之间的主要区别是什么?

主要区别在于易用性和性能。IronPDF 提供了一个更简单的 API,步骤更少,使分割 PDF 更容易,不会丢失格式。另一方面,iTextSharp 需要创建多个实例,如 PdfReader、PdfDocument 和 PdfWriter,可能更复杂。

我可以使用 C# 从 PDF 中提取特定页面吗?

可以,使用 IronPDF,您可以轻松地在 C# 中从 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 对物联网 (IoT) 有浓厚的兴趣,探索将硬件和软件集成的新方法。在空闲时间,他喜欢玩游戏和构建 Discord 机器人,将他对技术的热爱与创造力相结合。