フッターコンテンツにスキップ
製品比較

C#でのPDFの分割に関するiTextSharpとIronPDFの比較

PDF (Portable Document Format) ファイルは、ドキュメントの共有や提示に広く使用されており、時には PDF を複数のファイルに分割する必要がある場合があります。 特定のページを抽出したり、大きなドキュメントを小さなセクションに分割したり、各章に個別のファイルを作成したりするかどうかにかかわらず、PDF の分割はさまざまなシナリオで価値のある作業となります。

この記事では、C# を使用して PDF をどのように分割するかを学びます。 C# は多用途で強力な言語であり、PDF を比較的簡単に操作できるライブラリがいくつか存在します。 C# で PDF を分割するための次の 2 つのライブラリを検討します。

  1. iTextSharp
  2. IronPDF

iTextSharp を使用して C# で PDF を分割する方法

  1. まず、iText7 ライブラリをインストールします。
  2. 入力された PDF ファイルから PdfReader を作成します。
  3. PDF の内容を操作するために PdfDocument を使用します。
  4. 各分割ファイルのページ数を計算します。
  5. 初期のページ範囲の値を設定します。
  6. 各分割ファイルを処理するためにループを使用します。
  7. 現在の分割ファイル用に新しい PdfDocument を作成します。
  8. 元のドキュメントから新しいものにページをコピーします。
  9. 次のイテレーションのためにページ範囲の値を更新します。
  10. 完成した出力 PDF を保存します。
  11. すべてのファイルが作成されるまで繰り返します。
  12. 指定された分割ファイル数のプロセスを続行します。

IronPDF

C#における iTextSharp と IronPDF 間の PDF 分割の比較: 図 1 - IronPDF ウェブページ

IronPDF は、PDF ファイルを操作するために設計された強力な C# ライブラリです。 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 パッケージとその依存関係がプロジェクトにダウンロードおよびインストールされます。 インストールが完了すると、IronPDFをC#プロジェクトで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 パッケージとその依存関係がプロジェクトにダウンロードおよびインストールされます。 インストールが完了すると、PDF を扱うために C# プロジェクトで iTextSharp を使用し始めることができます。

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 を読み込むことにより、sourceFile という名前の PdfDocument オブジェクトが作成されます。
  2. 2 つの整数変数 firstPagelastPage が初期化されます。 これらは、分割するためのページ範囲を表します。
  3. totalPageInOneFile は、ソース PDF の総ページ数を指定された numberOfSplitFiles で割ることによって計算されます。
  4. 1 から numberOfSplitFiles までループが繰り返されます:
  5. newSplitPDF という名前の新しい PdfDocument オブジェクトが作成されます。
  6. firstPage から lastPage (含む) までのページが sourceFile から newSplitPDF にコピーされます。
  7. 結果として得られる小さな PDF は、指定された出力フォルダに「SplitPDF_IronPDF_1.pdf」(最初の分割の場合)のようなファイル名で保存されます。
  8. 次のイテレーションのために、firstPage および lastPage の値が更新されます。

注記

"input.pdf" を実際の入力 PDF ファイルのパスに置き換える必要があります。IronPDF ライブラリがプロジェクト内で正しくインストールされ、参照されていることを確認してください。

出力ファイルは次のように作成されます:

C#における iTextSharp と IronPDF 間の PDF 分割の比較: 図 3 - 作成された出力ファイル

iTextSharp を使用して C# で PDF を分割する

次に、iTextSharp を使用して 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 の 3 つのパラメーターを取ります。

PdfReader と PdfDocument の使用

SplitPdfUsingiTextSharp メソッド内:

  1. 指定された inputPdfPath から PDF を読み込むことにより、reader という名前の PdfReader オブジェクトが作成されます。
  2. reader を使用して doc という名前の PdfDocument オブジェクトが初期化されます。
  3. ソース PDF 内の総ページ数を numberOfSplitFiles で割って、各小さな PDF が含むべきページ数を決定します。

分割プロセス

1 から numberOfSplitFiles までループが繰り返されます:

  1. 指定された出力フォルダに「SplitPDF_iTextSharp_1.pdf」(最初の分割の場合)のようなファイル名で新しい小さな PDF ファイルが作成されます。
  2. この新しい PDF ドキュメント(pdfDocument)内で、元の doc からページがコピーされます:
  3. firstPage、lastPage (含む) がコピーされます。
  4. 小さな PDF が保存されます。
  5. 次のイテレーションのために、firstPage、lastPage の値が更新されます。

注記

iTextSharp ライブラリがプロジェクト内で正しくインストールされ、参照されていることを確認してください。 "input.pdf" を実際の入力 PDF ファイルのパスに置き換えてください。

C#における iTextSharp と IronPDF 間の PDF 分割の比較: 図 4 - 作成された出力ファイル

比較

iTextSharp と IronPDF を使用して 2 つの分割方法を比較するには、次のいくつかの要因に基づいて評価しましょう:

  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はPDFを読み込み、分割するページ範囲を指定する簡単なAPIを提供しており、結果のPDFで元のフォーマットが維持されることを保証します。

C#でPDFを分割する際のiTextSharpとIronPDFの主な違いは何ですか?

主な違いは、使いやすさとパフォーマンスにあります。IronPDFは、よりシンプルなAPIを提供し、ステップが少ないため、フォーマットを損なうことなくPDFを簡単に分割できます。一方、iTextSharpはPdfReaderPdfDocumentPdfWriterなどの複数のインスタンスを作成する必要があり、より複雑になる可能性があります。

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は現代のフレームワークを用いた開発や、構造の良い視覚的に魅力的なマニュアルの作成を楽しんでいます。

開発以外にも、CurtisはIoT(Internet of Things)への強い関心を持ち、ハードウェアとソフトウェアの統合方法を模索しています。余暇には、ゲームをしたりDiscordボットを作成したりして、技術に対する愛情と創造性を組み合わせています。