フッターコンテンツにスキップ
IRONPDFの使用

IronPDFでC#を使用して2つのPDFファイルを効率的に比較する方法

はじめに

PDFドキュメントをプログラムで比較することは、ドキュメントのリビジョンを追跡することから、法的ワークフローにおけるコンプライアンスを確保することまで、最新の.NET Coreアプリケーションにおける重要な要件です。 契約変更の検証、異なるバージョンの監視、品質保証プロセスの実装など、自動化されたPDFファイル比較は、開発者の時間を節約し、不一致を減らすのに役立ちます。

IronPDFは、強力なテキスト抽出機能と柔軟な文書比較オプションを組み合わせることで、C#を使用して2つのPDFファイルを比較するための合理的なアプローチを提供します。 このチュートリアルでは、IronPDFの直感的なAPIを使って2つのPDFドキュメントを効率的に比較する方法を、実践的なコード例を用いて説明します。

How to Efficiently Compare Two PDF Files Using C# with IronPDF:イメージ1 - IronPDF

はじめに:.NETプロジェクトのインストールとセットアップ

まず、.NETプロジェクトにNuGetパッケージマネージャ経由でIronPDFをインストールしてください:

Install-Package IronPdf
Install-Package IronPdf
SHELL

How to Efficiently Compare Two PDF Files Using C# with IronPDF:画像2 - インストール</a

または、.NET CLIを使用してリファレンスを追加します:

dotnet add package IronPdf
dotnet add package IronPdf
SHELL

LinuxまたはWindows環境の場合、プラットフォーム固有の手順については、ドキュメントを参照してください。 .NETパッケージがインストールされたら、ライセンスを設定します(開発用オプション):

IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY";
IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY";
IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY"
$vbLabelText   $csharpLabel

How to Efficiently Compare Two PDF Files Using C# with IronPDF:イメージ3 - 機能

基本的な比較:2つのPDFを比較する

PDF文書の比較の基本は、テキストコンテンツの抽出と比較です。 以下は、2つのPDFファイルを比較するサンプルコードです:

using IronPdf;
using System;

class PdfComparer
{
    public static void CompareSimple(string pdf1Path, string pdf2Path)
    {
        // Load two PDF documents
        var pdf1 = PdfDocument.FromFile(pdf1Path);
        var pdf2 = PdfDocument.FromFile(pdf2Path);
        // Extract text from both PDFs
        string text1 = pdf1.ExtractAllText();
        string text2 = pdf2.ExtractAllText();
        // Compare the two documents
        if (text1 == text2)
        {
            Console.WriteLine("PDF files are identical");
        }
        else
        {
            Console.WriteLine("PDFs have differences");
            // Find differences and calculate similarity
            double similarity = CalculateSimilarity(text1, text2);
            Console.WriteLine($"Comparison result: {similarity:P} similar");
        }
    }

    private static double CalculateSimilarity(string text1, string text2)
    {
        int maxLength = Math.Max(text1.Length, text2.Length);
        if (maxLength == 0) return 1.0;
        int differences = 0;
        int minLength = Math.Min(text1.Length, text2.Length);
        for (int i = 0; i < minLength; i++)
        {
            if (text1[i] != text2[i]) differences++;
        }
        differences += Math.Abs(text1.Length - text2.Length);
        return 1.0 - (double)differences / maxLength;
    }
}
using IronPdf;
using System;

class PdfComparer
{
    public static void CompareSimple(string pdf1Path, string pdf2Path)
    {
        // Load two PDF documents
        var pdf1 = PdfDocument.FromFile(pdf1Path);
        var pdf2 = PdfDocument.FromFile(pdf2Path);
        // Extract text from both PDFs
        string text1 = pdf1.ExtractAllText();
        string text2 = pdf2.ExtractAllText();
        // Compare the two documents
        if (text1 == text2)
        {
            Console.WriteLine("PDF files are identical");
        }
        else
        {
            Console.WriteLine("PDFs have differences");
            // Find differences and calculate similarity
            double similarity = CalculateSimilarity(text1, text2);
            Console.WriteLine($"Comparison result: {similarity:P} similar");
        }
    }

    private static double CalculateSimilarity(string text1, string text2)
    {
        int maxLength = Math.Max(text1.Length, text2.Length);
        if (maxLength == 0) return 1.0;
        int differences = 0;
        int minLength = Math.Min(text1.Length, text2.Length);
        for (int i = 0; i < minLength; i++)
        {
            if (text1[i] != text2[i]) differences++;
        }
        differences += Math.Abs(text1.Length - text2.Length);
        return 1.0 - (double)differences / maxLength;
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

このコードは、2つのPDFファイルをロードし、それらのテキストコンテンツ全体を抽出し、基本的な比較を実行します。 このメソッドは、ドキュメントの類似度を示す結果を提供し、ファイル間の違いを定量化するのに役立ちます。

入力

How to Efficiently Compare Two PDF Files Using C# with IronPDF:画像4 - サンプルPDF入力1

How to Efficiently Compare Two PDF Files Using C# with IronPDF:画像5 - サンプルPDF入力2

出力

How to Efficiently Compare Two PDF Files Using C# with IronPDF:イメージ6 - コンソール出力

高度な:ページごとのPDF比較

より詳細な分析には、PDF文書をページごとに比較して、変更箇所を正確に特定します:

public static void CompareByPage(string pdf1Path, string pdf2Path)
{
    // Using Comparer class pattern for the first PDF document
    var pdf1 = PdfDocument.FromFile(pdf1Path);
    var pdf2 = PdfDocument.FromFile(pdf2Path);
    int maxPages = Math.Max(pdf1.PageCount, pdf2.PageCount);
    for (int i = 0; i < maxPages; i++)
    {
        string page1Text = i < pdf1.PageCount ?
            pdf1.ExtractTextFromPage(i) : "";
        string page2Text = i < pdf2.PageCount ?
            pdf2.ExtractTextFromPage(i) : "";
        if (page1Text != page2Text)
        {
            Console.WriteLine($"Difference found on page {i + 1}");
            // Highlight differences in output
        }
    }
}
public static void CompareByPage(string pdf1Path, string pdf2Path)
{
    // Using Comparer class pattern for the first PDF document
    var pdf1 = PdfDocument.FromFile(pdf1Path);
    var pdf2 = PdfDocument.FromFile(pdf2Path);
    int maxPages = Math.Max(pdf1.PageCount, pdf2.PageCount);
    for (int i = 0; i < maxPages; i++)
    {
        string page1Text = i < pdf1.PageCount ?
            pdf1.ExtractTextFromPage(i) : "";
        string page2Text = i < pdf2.PageCount ?
            pdf2.ExtractTextFromPage(i) : "";
        if (page1Text != page2Text)
        {
            Console.WriteLine($"Difference found on page {i + 1}");
            // Highlight differences in output
        }
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

この比較方法では、各ページを繰り返し、コンテンツを個別に比較します。 このプロセスでは、ページ数の異なるPDFを優雅に処理するため、ページが更新された可能性のある複数のPDF文書を比較する場合に最適です。

複数のPDFドキュメントの比較

複数のPDF文書を比較するシステムを強化するには、Comparerクラスを拡張してください:

public class MultiPdfComparer
{
    public static void CompareMultiple(params string[] pdfPaths)
    {
        if (pdfPaths.Length < 2) return;
        // Load first PDF document as reference
        var referencePdf = PdfDocument.FromFile(pdfPaths[0]);
        string referenceText = referencePdf.ExtractAllText();
        // Compare with other PDF files
        for (int i = 1; i < pdfPaths.Length; i++)
        {
            var currentPdf = PdfDocument.FromFile(pdfPaths[i]);
            string currentText = currentPdf.ExtractAllText();
            if (referenceText != currentText)
            {
                Console.WriteLine($"PDF {i} differs from reference");
            }
        }
        // Results saved for further processing
    }
}
public class MultiPdfComparer
{
    public static void CompareMultiple(params string[] pdfPaths)
    {
        if (pdfPaths.Length < 2) return;
        // Load first PDF document as reference
        var referencePdf = PdfDocument.FromFile(pdfPaths[0]);
        string referenceText = referencePdf.ExtractAllText();
        // Compare with other PDF files
        for (int i = 1; i < pdfPaths.Length; i++)
        {
            var currentPdf = PdfDocument.FromFile(pdfPaths[i]);
            string currentText = currentPdf.ExtractAllText();
            if (referenceText != currentText)
            {
                Console.WriteLine($"PDF {i} differs from reference");
            }
        }
        // Results saved for further processing
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

このアプローチは、開発者が複数のPDF文書を参照文書と比較することを可能にし、バッチ処理要件に最適です。

出力

How to Efficiently Compare Two PDF Files Using C# with IronPDF:画像7 - 複数のPDF出力を比較する

パスワードで保護されたPDFを扱う

IronPdfは簡単なステップで暗号化されたPDFドキュメントをシームレスに処理します。 保護されたファイルをロードするときにパスワードを渡します:

public static void CompareSecuredPdfs(string pdf1Path, string pdf2Path,
                                      string password1, string password2)
{
    // Load and compare two PDFs with passwords
    var pdf1 = PdfDocument.FromFile(pdf1Path, password1);
    var pdf2 = PdfDocument.FromFile(pdf2Path, password2);
    string text1 = pdf1.ExtractAllText();
    string text2 = pdf2.ExtractAllText();
    // Compare two PDF files and save results
    bool identical = text1.Equals(text2);
    var comparisonResult = identical ? "identical" : "different";
    Console.WriteLine($"Secured PDFs are {comparisonResult}");
    // Accept or reject changes based on comparison
}
public static void CompareSecuredPdfs(string pdf1Path, string pdf2Path,
                                      string password1, string password2)
{
    // Load and compare two PDFs with passwords
    var pdf1 = PdfDocument.FromFile(pdf1Path, password1);
    var pdf2 = PdfDocument.FromFile(pdf2Path, password2);
    string text1 = pdf1.ExtractAllText();
    string text2 = pdf2.ExtractAllText();
    // Compare two PDF files and save results
    bool identical = text1.Equals(text2);
    var comparisonResult = identical ? "identical" : "different";
    Console.WriteLine($"Secured PDFs are {comparisonResult}");
    // Accept or reject changes based on comparison
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

FromFileメソッドを呼び出すときにパスワードを渡すことで、暗号化された2つのPDFファイルを比較することができます。

比較レポートの作成

詳細な比較結果を作成し、レビュー用に保存します:

public static void CreateComparisonReport(string pdf1Path, string pdf2Path)
{
    var pdf1 = PdfDocument.FromFile(pdf1Path);
    var pdf2 = PdfDocument.FromFile(pdf2Path);
    // Extract and compare
    var differences = new List<string>();
    for (int i = 0; i < Math.Max(pdf1.PageCount, pdf2.PageCount); i++)
    {
        // Extract page text (guard for missing pages)
        string page1Text = i < pdf1.PageCount ? pdf1.ExtractTextFromPage(i) ?? string.Empty : string.Empty;
        string page2Text = i < pdf2.PageCount ? pdf2.ExtractTextFromPage(i) ?? string.Empty : string.Empty;
        // If identical, no entry needed
        if (page1Text == page2Text) continue;
        // Compute a simple similarity score (0..1)
        double similarity = CalculateSimilarity(page1Text, page2Text);
        differences.Add($"Page {i + 1}: Similarity {similarity:P}. Lengths: [{page1Text.Length}, {page2Text.Length}].");
    }
    // Create output report
    var renderer = new ChromePdfRenderer();
    var sb = new System.Text.StringBuilder();
    sb.Append("<h1>PDF Comparison Results</h1>");
    sb.Append("<p>Total differences: {differences.Count}</p>");
    if (differences.Count > 0)
    {
        sb.Append("<ol>");
        foreach (var d in differences)
        {
            sb.Append($"<li><pre style='white-space:pre-wrap'>{d}</pre></li>");
        }
        sb.Append("</ol>");
    }
    else
    {
        sb.Append("<p>No page-level differences detected.</p>");
    }
    var reportHtml = sb.ToString();
    var reportPdf = renderer.RenderHtmlAsPdf(reportHtml);
    reportPdf.SaveAs("comparison-report.pdf");
}
public static void CreateComparisonReport(string pdf1Path, string pdf2Path)
{
    var pdf1 = PdfDocument.FromFile(pdf1Path);
    var pdf2 = PdfDocument.FromFile(pdf2Path);
    // Extract and compare
    var differences = new List<string>();
    for (int i = 0; i < Math.Max(pdf1.PageCount, pdf2.PageCount); i++)
    {
        // Extract page text (guard for missing pages)
        string page1Text = i < pdf1.PageCount ? pdf1.ExtractTextFromPage(i) ?? string.Empty : string.Empty;
        string page2Text = i < pdf2.PageCount ? pdf2.ExtractTextFromPage(i) ?? string.Empty : string.Empty;
        // If identical, no entry needed
        if (page1Text == page2Text) continue;
        // Compute a simple similarity score (0..1)
        double similarity = CalculateSimilarity(page1Text, page2Text);
        differences.Add($"Page {i + 1}: Similarity {similarity:P}. Lengths: [{page1Text.Length}, {page2Text.Length}].");
    }
    // Create output report
    var renderer = new ChromePdfRenderer();
    var sb = new System.Text.StringBuilder();
    sb.Append("<h1>PDF Comparison Results</h1>");
    sb.Append("<p>Total differences: {differences.Count}</p>");
    if (differences.Count > 0)
    {
        sb.Append("<ol>");
        foreach (var d in differences)
        {
            sb.Append($"<li><pre style='white-space:pre-wrap'>{d}</pre></li>");
        }
        sb.Append("</ol>");
    }
    else
    {
        sb.Append("<p>No page-level differences detected.</p>");
    }
    var reportHtml = sb.ToString();
    var reportPdf = renderer.RenderHtmlAsPdf(reportHtml);
    reportPdf.SaveAs("comparison-report.pdf");
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

出力

How to Efficiently Compare Two PDF Files Using C# with IronPDF:画像8 - 比較レポート出力

IronPDF を選ぶ理由

IronPDFは、わかりやすいAPIによってPDFの比較に優れています。 ライブラリは.NET Core、.NET Frameworkをサポートし、Windows、Linux、macOSで動作します。 主な利点は次のとおりです。

  • PDFファイルを比較するシンプルなAPI
  • 異なるバージョンのPDFのサポート
  • リビジョンの組み込み処理
  • 開発・作成が容易な比較ツール
  • 包括的なドキュメントとサポート

How to Efficiently Compare Two PDF Files Using C# with IronPDF:画像9 - クロスプラットフォームの互換性

結論

IronPdfは複雑なPDFドキュメントの比較作業を管理しやすい操作に変換します。 文書管理システムを作成する場合でも、C#を使用して2つのPDFファイルを比較する場合でも、IronPdfは必要なすべてのツールを提供します。

How to Efficiently Compare Two PDF Files Using C# with IronPDF:画像10 - C#を使って2つのPDFファイルを比較する - IronPDF

詳細はこちら IronPDF の無料トライアルをダウンロードし、プロフェッショナル グレードの比較機能を使用して PDF ファイルを設定します。 本番環境への導入については、ライセンスオプションを検討し、詳細については包括的なドキュメントを参照してください。

How to Efficiently Compare Two PDF Files Using C# with IronPDF:画像11 - ライセンス

よくある質問

C#を使用して2つのPDFファイルを比較するにはどうすればよいですか?

IronPDFの強力なPDF比較機能を利用することで、C#を使って2つのPDFファイルを比較することができ、2つのPDFドキュメント間のテキスト、画像、レイアウトの違いを識別することができます。

PDFの比較にIronPdfを使用する利点は何ですか?

IronPDFはPDFファイルを比較するシンプルで効率的な方法を提供します。様々な比較モードをサポートし、C#プロジェクトとシームレスに統合します。

IronPDFは大規模なPDFファイルの比較を処理できますか?

IronPDFは大きなPDFファイルを効率的に処理するように設計されており、パフォーマンスを損なうことなく広範なドキュメントを比較するのに適しています。

IronPdfはPDFのビジュアル比較をサポートしていますか?

IronPdfはレイアウトや画像の違いをハイライトすることでPDFの視覚的な比較を可能にし、ドキュメント間の変更を包括的に表示します。

IronPDFを使用してPDF比較を自動化することは可能ですか?

そうです。C#アプリケーションでIronPDFを使ってPDFの比較処理を自動化することができます。

IronPdfはPDFファイルのどのような違いを検出できますか?

IronPdfはテキスト、グラフィック、レイアウトの違いを検出し、PDFファイルのコンテンツ全体を徹底的に比較します。

IronPdfはどのようにしてPDF比較の正確性を確保しているのですか?

IronPdfは高度なアルゴリズムでPDFの内容を綿密に比較し、微妙な違いを見落とすリスクを最小限に抑えることで、正確さを保証します。

IronPDFを他の.NETアプリケーションと統合してPDFを比較できますか?

IronPDFは.NETアプリケーションとシームレスに統合できるように設計されており、開発者は既存のソフトウェアソリューションにPDF比較機能を組み込むことができます。

IronPDFを使うのにPDF比較の経験は必要ですか?

経験は問いません。IronPdfはユーザーフレンドリーなツールと包括的なドキュメントを提供し、PDF操作が初めての方でもPDFを比較するプロセスをガイドします。

IronPDFのPDF比較機能のデモやトライアルはありますか?

IronPDFは無料トライアルを提供しており、ご購入前にPDF比較の機能をお試しいただけます。

カーティス・チャウ
テクニカルライター

Curtis Chauは、カールトン大学でコンピュータサイエンスの学士号を取得し、Node.js、TypeScript、JavaScript、およびReactに精通したフロントエンド開発を専門としています。直感的で美しいユーザーインターフェースを作成することに情熱を持ち、Curtisは現代のフレームワークを用いた開発や、構造の良い視覚的に魅力的なマニュアルの作成を楽しんでいます。

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