USING IRONPDF How to Compare Two PDF Files in C# Curtis Chau 更新:2025年11月25日 下載 IronPDF NuGet 下載 DLL 下載 Windows 安裝程式 開始免費試用 法學碩士副本 法學碩士副本 將頁面複製為 Markdown 格式,用於 LLMs 在 ChatGPT 中打開 請向 ChatGPT 諮詢此頁面 在雙子座打開 請向 Gemini 詢問此頁面 在 Grok 中打開 向 Grok 詢問此頁面 打開困惑 向 Perplexity 詢問有關此頁面的信息 分享 在 Facebook 上分享 分享到 X(Twitter) 在 LinkedIn 上分享 複製連結 電子郵件文章 以程式設計方式比較 PDF 文件對於追蹤變更、驗證不同版本以及自動化品質保證工作流程至關重要。 無論您是需要比較兩個 PDF 文件以進行文件管理,還是需要查找合約修訂中的差異, IronPDF都提供了一個簡化的解決方案,用於在 C# 中比較 PDF 文件。 本教學課程示範如何使用 IronPDF 的文字擷取功能比較兩個 PDF 文檔,從基本比較到建立詳細的差異報告。 您將學習實用的技術,並了解可在 Windows、Linux、macOS、Docker 和雲端平台上運行的程式碼範例。 如何使用 IronPDF 和 C# 比較兩個 PDF 檔案:圖 1 - IronPDF 前提條件和設置 開始之前,請確保已安裝: Visual Studio 2019 或更高版本 .NET Framework 4.6.2+ 或 .NET Core 3.1+ 具備基本的 C# 知識 安裝 IronPDF .NET 套件 在您的 .NET 專案中透過 NuGet 套件管理器安裝 IronPDF: Install-Package IronPdf Install-Package IronPdf SHELL 如何使用 IronPDF 透過 C# 比較兩個 PDF 檔案:圖 2 - 安裝 或使用 .NET CLI: dotnet add package IronPdf dotnet add package IronPdf SHELL 在檔案中加入必要的命名空間參考: using IronPdf; using System; using IronPdf; using System; Imports IronPdf Imports System $vbLabelText $csharpLabel 如何使用 IronPDF 透過 C# 比較兩個 PDF 檔案:圖 3 - 功能 PDF文件基本比較 讓我們從範例程式碼開始,透過提取和比較 PDF 文件的文字內容來比較它們: public class BasicPdfComparer { public static bool ComparePdfFiles(string firstPdfPath, string secondPdfPath) { // Load two PDF documents var pdf1 = PdfDocument.FromFile(firstPdfPath); var pdf2 = PdfDocument.FromFile(secondPdfPath); // Extract all text from both PDFs string text1 = pdf1.ExtractAllText(); string text2 = pdf2.ExtractAllText(); // Compare the two documents bool areIdentical = text1 == text2; // Find differences and calculate similarity double similarity = CalculateSimilarity(text1, text2); Console.WriteLine($"Documents are {(areIdentical ? "identical" : "different")}"); Console.WriteLine($"Similarity: {similarity:F2}%"); return areIdentical; } private static double CalculateSimilarity(string text1, string text2) { if (text1 == text2) return 100.0; if (string.IsNullOrEmpty(text1) || string.IsNullOrEmpty(text2)) return 0.0; int matchingChars = 0; int minLength = Math.Min(text1.Length, text2.Length); for (int i = 0; i < minLength; i++) { if (text1[i] == text2[i]) matchingChars++; } return (double)matchingChars / Math.Max(text1.Length, text2.Length) * 100; } } public class BasicPdfComparer { public static bool ComparePdfFiles(string firstPdfPath, string secondPdfPath) { // Load two PDF documents var pdf1 = PdfDocument.FromFile(firstPdfPath); var pdf2 = PdfDocument.FromFile(secondPdfPath); // Extract all text from both PDFs string text1 = pdf1.ExtractAllText(); string text2 = pdf2.ExtractAllText(); // Compare the two documents bool areIdentical = text1 == text2; // Find differences and calculate similarity double similarity = CalculateSimilarity(text1, text2); Console.WriteLine($"Documents are {(areIdentical ? "identical" : "different")}"); Console.WriteLine($"Similarity: {similarity:F2}%"); return areIdentical; } private static double CalculateSimilarity(string text1, string text2) { if (text1 == text2) return 100.0; if (string.IsNullOrEmpty(text1) || string.IsNullOrEmpty(text2)) return 0.0; int matchingChars = 0; int minLength = Math.Min(text1.Length, text2.Length); for (int i = 0; i < minLength; i++) { if (text1[i] == text2[i]) matchingChars++; } return (double)matchingChars / Math.Max(text1.Length, text2.Length) * 100; } } Imports System Public Class BasicPdfComparer Public Shared Function ComparePdfFiles(firstPdfPath As String, secondPdfPath As String) As Boolean ' Load two PDF documents Dim pdf1 = PdfDocument.FromFile(firstPdfPath) Dim pdf2 = PdfDocument.FromFile(secondPdfPath) ' Extract all text from both PDFs Dim text1 As String = pdf1.ExtractAllText() Dim text2 As String = pdf2.ExtractAllText() ' Compare the two documents Dim areIdentical As Boolean = text1 = text2 ' Find differences and calculate similarity Dim similarity As Double = CalculateSimilarity(text1, text2) Console.WriteLine($"Documents are {(If(areIdentical, "identical", "different"))}") Console.WriteLine($"Similarity: {similarity:F2}%") Return areIdentical End Function Private Shared Function CalculateSimilarity(text1 As String, text2 As String) As Double If text1 = text2 Then Return 100.0 If String.IsNullOrEmpty(text1) OrElse String.IsNullOrEmpty(text2) Then Return 0.0 Dim matchingChars As Integer = 0 Dim minLength As Integer = Math.Min(text1.Length, text2.Length) For i As Integer = 0 To minLength - 1 If text1(i) = text2(i) Then matchingChars += 1 Next Return matchingChars / Math.Max(text1.Length, text2.Length) * 100 End Function End Class $vbLabelText $csharpLabel 這段程式碼使用 IronPDF 的PdfDocument.FromFile()方法載入兩個 PDF 文件,提取所有文字內容,並執行直接字串比較。 比較方法可以提供指標來識別文件的匹配程度。 輸入 如何使用 IronPDF 和 C# 比較兩個 PDF 檔案:圖 4 - 範例 PDF 輸入 1 如何使用 IronPDF 和 C# 比較兩個 PDF 檔案:圖 5 - 範例 PDF 輸入 2 輸出 如何使用 IronPDF 和 C# 比較兩個 PDF 檔案:圖 6 - 控制台輸出 逐頁比較法 如需更詳細的分析,請逐頁比較兩個 PDF 文件,以確定差異的具體位置: public static void ComparePageByPage(string firstPdfPath, string secondPdfPath) { // Load two files var pdf1 = PdfDocument.FromFile(firstPdfPath); var pdf2 = PdfDocument.FromFile(secondPdfPath); int maxPages = Math.Max(pdf1.PageCount, pdf2.PageCount); int differencesFound = 0; for (int i = 0; i < maxPages; i++) { // Process each page string page1Text = i < pdf1.PageCount ? pdf1.ExtractTextFromPage(i) : ""; string page2Text = i < pdf2.PageCount ? pdf2.ExtractTextFromPage(i) : ""; if (page1Text != page2Text) { differencesFound++; Console.WriteLine($"Page {i + 1}: Differences detected"); } else { Console.WriteLine($"Page {i + 1}: Identical"); } } Console.WriteLine($"\nSummary: {differencesFound} page(s) with changes"); } public static void ComparePageByPage(string firstPdfPath, string secondPdfPath) { // Load two files var pdf1 = PdfDocument.FromFile(firstPdfPath); var pdf2 = PdfDocument.FromFile(secondPdfPath); int maxPages = Math.Max(pdf1.PageCount, pdf2.PageCount); int differencesFound = 0; for (int i = 0; i < maxPages; i++) { // Process each page string page1Text = i < pdf1.PageCount ? pdf1.ExtractTextFromPage(i) : ""; string page2Text = i < pdf2.PageCount ? pdf2.ExtractTextFromPage(i) : ""; if (page1Text != page2Text) { differencesFound++; Console.WriteLine($"Page {i + 1}: Differences detected"); } else { Console.WriteLine($"Page {i + 1}: Identical"); } } Console.WriteLine($"\nSummary: {differencesFound} page(s) with changes"); } Public Shared Sub ComparePageByPage(firstPdfPath As String, secondPdfPath As String) ' Load two files Dim pdf1 = PdfDocument.FromFile(firstPdfPath) Dim pdf2 = PdfDocument.FromFile(secondPdfPath) Dim maxPages As Integer = Math.Max(pdf1.PageCount, pdf2.PageCount) Dim differencesFound As Integer = 0 For i As Integer = 0 To maxPages - 1 ' Process each page Dim page1Text As String = If(i < pdf1.PageCount, pdf1.ExtractTextFromPage(i), "") Dim page2Text As String = If(i < pdf2.PageCount, pdf2.ExtractTextFromPage(i), "") If page1Text <> page2Text Then differencesFound += 1 Console.WriteLine($"Page {i + 1}: Differences detected") Else Console.WriteLine($"Page {i + 1}: Identical") End If Next Console.WriteLine(vbCrLf & $"Summary: {differencesFound} page(s) with changes") End Sub $vbLabelText $csharpLabel ExtractTextFromPage()方法允許從特定頁面進行有針對性擷取。 這種方法可以幫助開發人員找出不同版本 PDF 文件之間的差異。 使用比較器類別模式 建立專用的比較器類別來增強比較功能: public class PdfComparer { private PdfDocument pdf1; private PdfDocument pdf2; private bool disposed; public PdfComparer(string file1Path, string file2Path) { // Load the two PDFs pdf1 = PdfDocument.FromFile(file1Path); pdf2 = PdfDocument.FromFile(file2Path); } public ComparisonResult Compare() { var result = new ComparisonResult(); // Compare PDF documents string text1 = pdf1?.ExtractAllText() ?? string.Empty; string text2 = pdf2?.ExtractAllText() ?? string.Empty; result.AreIdentical = string.Equals(text1, text2, StringComparison.Ordinal); result.SimilarityPercent = CalculateSimilarity(text1, text2); result.Differences = FindDifferences(text1, text2); return result; } private List<string> FindDifferences(string text1, string text2) { var differences = new List<string>(); // Normalize nulls text1 ??= string.Empty; text2 ??= string.Empty; if (string.Equals(text1, text2, StringComparison.Ordinal)) return differences; // Page-aware comparisons aren't possible here because we only have full-text; // produce a concise, actionable difference entry: int min = Math.Min(text1.Length, text2.Length); int firstDiff = -1; for (int i = 0; i < min; i++) { if (text1[i] != text2[i]) { firstDiff = i; break; } } if (firstDiff == -1 && text1.Length != text2.Length) { // No differing character in the overlap, but lengths differ firstDiff = min; } // Create short excerpts around the first difference for context int excerptLength = 200; string excerpt1 = string.Empty; string excerpt2 = string.Empty; if (firstDiff >= 0) { int start1 = Math.Max(0, firstDiff); int len1 = Math.Min(excerptLength, Math.Max(0, text1.Length - start1)); excerpt1 = start1 < text1.Length ? text1.Substring(start1, len1) : string.Empty; int start2 = Math.Max(0, firstDiff); int len2 = Math.Min(excerptLength, Math.Max(0, text2.Length - start2)); excerpt2 = start2 < text2.Length ? text2.Substring(start2, len2) : string.Empty; } // HTML-encode excerpts if they will be embedded into HTML reports string safeExcerpt1 = System.Net.WebUtility.HtmlEncode(excerpt1); string safeExcerpt2 = System.Net.WebUtility.HtmlEncode(excerpt2); double similarity = CalculateSimilarity(text1, text2); differences.Add($"Similarity: {similarity:F2}%. Lengths: [{text1.Length}, {text2.Length}]. First difference index: {firstDiff}. Excerpt1: \"{safeExcerpt1}\" Excerpt2: \"{safeExcerpt2}\""); return differences; } public void Close() { Dispose(); } public void Dispose() { if (disposed) return; disposed = true; pdf1?.Dispose(); pdf2?.Dispose(); } } public class ComparisonResult { // True when extracted text is exactly the same public bool AreIdentical { get; set; } // Similarity expressed as percent (0..100) public double SimilarityPercent { get; set; } // Human readable difference entries public List<string> Differences { get; set; } = new List<string>(); } public class PdfComparer { private PdfDocument pdf1; private PdfDocument pdf2; private bool disposed; public PdfComparer(string file1Path, string file2Path) { // Load the two PDFs pdf1 = PdfDocument.FromFile(file1Path); pdf2 = PdfDocument.FromFile(file2Path); } public ComparisonResult Compare() { var result = new ComparisonResult(); // Compare PDF documents string text1 = pdf1?.ExtractAllText() ?? string.Empty; string text2 = pdf2?.ExtractAllText() ?? string.Empty; result.AreIdentical = string.Equals(text1, text2, StringComparison.Ordinal); result.SimilarityPercent = CalculateSimilarity(text1, text2); result.Differences = FindDifferences(text1, text2); return result; } private List<string> FindDifferences(string text1, string text2) { var differences = new List<string>(); // Normalize nulls text1 ??= string.Empty; text2 ??= string.Empty; if (string.Equals(text1, text2, StringComparison.Ordinal)) return differences; // Page-aware comparisons aren't possible here because we only have full-text; // produce a concise, actionable difference entry: int min = Math.Min(text1.Length, text2.Length); int firstDiff = -1; for (int i = 0; i < min; i++) { if (text1[i] != text2[i]) { firstDiff = i; break; } } if (firstDiff == -1 && text1.Length != text2.Length) { // No differing character in the overlap, but lengths differ firstDiff = min; } // Create short excerpts around the first difference for context int excerptLength = 200; string excerpt1 = string.Empty; string excerpt2 = string.Empty; if (firstDiff >= 0) { int start1 = Math.Max(0, firstDiff); int len1 = Math.Min(excerptLength, Math.Max(0, text1.Length - start1)); excerpt1 = start1 < text1.Length ? text1.Substring(start1, len1) : string.Empty; int start2 = Math.Max(0, firstDiff); int len2 = Math.Min(excerptLength, Math.Max(0, text2.Length - start2)); excerpt2 = start2 < text2.Length ? text2.Substring(start2, len2) : string.Empty; } // HTML-encode excerpts if they will be embedded into HTML reports string safeExcerpt1 = System.Net.WebUtility.HtmlEncode(excerpt1); string safeExcerpt2 = System.Net.WebUtility.HtmlEncode(excerpt2); double similarity = CalculateSimilarity(text1, text2); differences.Add($"Similarity: {similarity:F2}%. Lengths: [{text1.Length}, {text2.Length}]. First difference index: {firstDiff}. Excerpt1: \"{safeExcerpt1}\" Excerpt2: \"{safeExcerpt2}\""); return differences; } public void Close() { Dispose(); } public void Dispose() { if (disposed) return; disposed = true; pdf1?.Dispose(); pdf2?.Dispose(); } } public class ComparisonResult { // True when extracted text is exactly the same public bool AreIdentical { get; set; } // Similarity expressed as percent (0..100) public double SimilarityPercent { get; set; } // Human readable difference entries public List<string> Differences { get; set; } = new List<string>(); } Imports System Imports System.Collections.Generic Imports System.Net Public Class PdfComparer Implements IDisposable Private pdf1 As PdfDocument Private pdf2 As PdfDocument Private disposed As Boolean Public Sub New(file1Path As String, file2Path As String) ' Load the two PDFs pdf1 = PdfDocument.FromFile(file1Path) pdf2 = PdfDocument.FromFile(file2Path) End Sub Public Function Compare() As ComparisonResult Dim result As New ComparisonResult() ' Compare PDF documents Dim text1 As String = If(pdf1?.ExtractAllText(), String.Empty) Dim text2 As String = If(pdf2?.ExtractAllText(), String.Empty) result.AreIdentical = String.Equals(text1, text2, StringComparison.Ordinal) result.SimilarityPercent = CalculateSimilarity(text1, text2) result.Differences = FindDifferences(text1, text2) Return result End Function Private Function FindDifferences(text1 As String, text2 As String) As List(Of String) Dim differences As New List(Of String)() ' Normalize nulls text1 = If(text1, String.Empty) text2 = If(text2, String.Empty) If String.Equals(text1, text2, StringComparison.Ordinal) Then Return differences End If ' Page-aware comparisons aren't possible here because we only have full-text; ' produce a concise, actionable difference entry: Dim min As Integer = Math.Min(text1.Length, text2.Length) Dim firstDiff As Integer = -1 For i As Integer = 0 To min - 1 If text1(i) <> text2(i) Then firstDiff = i Exit For End If Next If firstDiff = -1 AndAlso text1.Length <> text2.Length Then ' No differing character in the overlap, but lengths differ firstDiff = min End If ' Create short excerpts around the first difference for context Dim excerptLength As Integer = 200 Dim excerpt1 As String = String.Empty Dim excerpt2 As String = String.Empty If firstDiff >= 0 Then Dim start1 As Integer = Math.Max(0, firstDiff) Dim len1 As Integer = Math.Min(excerptLength, Math.Max(0, text1.Length - start1)) excerpt1 = If(start1 < text1.Length, text1.Substring(start1, len1), String.Empty) Dim start2 As Integer = Math.Max(0, firstDiff) Dim len2 As Integer = Math.Min(excerptLength, Math.Max(0, text2.Length - start2)) excerpt2 = If(start2 < text2.Length, text2.Substring(start2, len2), String.Empty) End If ' HTML-encode excerpts if they will be embedded into HTML reports Dim safeExcerpt1 As String = WebUtility.HtmlEncode(excerpt1) Dim safeExcerpt2 As String = WebUtility.HtmlEncode(excerpt2) Dim similarity As Double = CalculateSimilarity(text1, text2) differences.Add($"Similarity: {similarity:F2}%. Lengths: [{text1.Length}, {text2.Length}]. First difference index: {firstDiff}. Excerpt1: ""{safeExcerpt1}"" Excerpt2: ""{safeExcerpt2}""") Return differences End Function Public Sub Close() Dispose() End Sub Public Sub Dispose() Implements IDisposable.Dispose If disposed Then Return disposed = True pdf1?.Dispose() pdf2?.Dispose() End Sub End Class Public Class ComparisonResult ' True when extracted text is exactly the same Public Property AreIdentical As Boolean ' Similarity expressed as percent (0..100) Public Property SimilarityPercent As Double ' Human readable difference entries Public Property Differences As List(Of String) = New List(Of String)() End Class $vbLabelText $csharpLabel 這種類別結構提供了一種簡潔的方法來比較 PDF 文檔,同時也能正確地管理文檔物件和引用。 輸出 如何使用 IronPDF 和 C# 比較兩個 PDF 檔案:圖 7 - 比較器類別模式輸出 建立視覺化比較報告 產生一份基於 HTML 的報告,突出顯示兩個文件之間的差異,並將其儲存為 PDF 文件: public static void CreateComparisonReport(string pdf1Path, string pdf2Path, string outputPath) { // Load PDFs for comparison var pdf1 = PdfDocument.FromFile(pdf1Path); var pdf2 = PdfDocument.FromFile(pdf2Path); // Build HTML report with details string htmlReport = @" <html> <head> <style> body { font-family: Arial, sans-serif; margin: 20px; } .identical { color: green; } .different { color: red; } table { width: 100%; border-collapse: collapse; } th, td { border: 1px solid #ddd; padding: 8px; } </style> </head> <body> <h1>PDF Comparison Report</h1> <table> <tr><th>Page</th><th>Status</th></tr>"; // Process each page for (int i = 0; i < Math.Max(pdf1.PageCount, pdf2.PageCount); i++) { string page1 = i < pdf1.PageCount ? pdf1.ExtractTextFromPage(i) : ""; string page2 = i < pdf2.PageCount ? pdf2.ExtractTextFromPage(i) : ""; bool identical = page1 == page2; string status = identical ? "Identical" : "Different"; htmlReport += $"<tr><td>Page {i + 1}</td><td class='{status.ToLower()}'>{status}</td></tr>"; } htmlReport += "</table></body></html>"; // Create and save the report var renderer = new ChromePdfRenderer(); var reportPdf = renderer.RenderHtmlAsPdf(htmlReport); reportPdf.SaveAs(outputPath); Console.WriteLine($"Report saved to: {outputPath}"); } public static void CreateComparisonReport(string pdf1Path, string pdf2Path, string outputPath) { // Load PDFs for comparison var pdf1 = PdfDocument.FromFile(pdf1Path); var pdf2 = PdfDocument.FromFile(pdf2Path); // Build HTML report with details string htmlReport = @" <html> <head> <style> body { font-family: Arial, sans-serif; margin: 20px; } .identical { color: green; } .different { color: red; } table { width: 100%; border-collapse: collapse; } th, td { border: 1px solid #ddd; padding: 8px; } </style> </head> <body> <h1>PDF Comparison Report</h1> <table> <tr><th>Page</th><th>Status</th></tr>"; // Process each page for (int i = 0; i < Math.Max(pdf1.PageCount, pdf2.PageCount); i++) { string page1 = i < pdf1.PageCount ? pdf1.ExtractTextFromPage(i) : ""; string page2 = i < pdf2.PageCount ? pdf2.ExtractTextFromPage(i) : ""; bool identical = page1 == page2; string status = identical ? "Identical" : "Different"; htmlReport += $"<tr><td>Page {i + 1}</td><td class='{status.ToLower()}'>{status}</td></tr>"; } htmlReport += "</table></body></html>"; // Create and save the report var renderer = new ChromePdfRenderer(); var reportPdf = renderer.RenderHtmlAsPdf(htmlReport); reportPdf.SaveAs(outputPath); Console.WriteLine($"Report saved to: {outputPath}"); } Imports System Public Shared Sub CreateComparisonReport(pdf1Path As String, pdf2Path As String, outputPath As String) ' Load PDFs for comparison Dim pdf1 = PdfDocument.FromFile(pdf1Path) Dim pdf2 = PdfDocument.FromFile(pdf2Path) ' Build HTML report with details Dim htmlReport As String = " <html> <head> <style> body { font-family: Arial, sans-serif; margin: 20px; } .identical { color: green; } .different { color: red; } table { width: 100%; border-collapse: collapse; } th, td { border: 1px solid #ddd; padding: 8px; } </style> </head> <body> <h1>PDF Comparison Report</h1> <table> <tr><th>Page</th><th>Status</th></tr>" ' Process each page For i As Integer = 0 To Math.Max(pdf1.PageCount, pdf2.PageCount) - 1 Dim page1 As String = If(i < pdf1.PageCount, pdf1.ExtractTextFromPage(i), "") Dim page2 As String = If(i < pdf2.PageCount, pdf2.ExtractTextFromPage(i), "") Dim identical As Boolean = page1 = page2 Dim status As String = If(identical, "Identical", "Different") htmlReport &= $"<tr><td>Page {i + 1}</td><td class='{status.ToLower()}'>{status}</td></tr>" Next htmlReport &= "</table></body></html>" ' Create and save the report Dim renderer = New ChromePdfRenderer() Dim reportPdf = renderer.RenderHtmlAsPdf(htmlReport) reportPdf.SaveAs(outputPath) Console.WriteLine($"Report saved to: {outputPath}") End Sub $vbLabelText $csharpLabel 這段程式碼示範如何建立包含對比結果的專業 PDF 文件。 報告已儲存到指定路徑。 比較多個PDF文檔 當您需要同時比較多個PDF文件時,請使用以下方法: public static void CompareMultiplePdfs(params string[] pdfPaths) { if (pdfPaths.Length < 2) { Console.WriteLine("Need at least two files to compare"); return; } // Load multiple PDF documents var pdfs = new List<PdfDocument>(); foreach (var path in pdfPaths) { pdfs.Add(PdfDocument.FromFile(path)); } // Compare all documents for (int i = 0; i < pdfs.Count - 1; i++) { for (int j = i + 1; j < pdfs.Count; j++) { string text1 = pdfs[i].ExtractAllText(); string text2 = pdfs[j].ExtractAllText(); bool identical = text1 == text2; Console.WriteLine($"File {i+1} vs File {j+1}: {(identical ? "Identical" : "Different")}"); } } // Close all documents pdfs.ForEach(pdf => pdf.Dispose()); } public static void CompareMultiplePdfs(params string[] pdfPaths) { if (pdfPaths.Length < 2) { Console.WriteLine("Need at least two files to compare"); return; } // Load multiple PDF documents var pdfs = new List<PdfDocument>(); foreach (var path in pdfPaths) { pdfs.Add(PdfDocument.FromFile(path)); } // Compare all documents for (int i = 0; i < pdfs.Count - 1; i++) { for (int j = i + 1; j < pdfs.Count; j++) { string text1 = pdfs[i].ExtractAllText(); string text2 = pdfs[j].ExtractAllText(); bool identical = text1 == text2; Console.WriteLine($"File {i+1} vs File {j+1}: {(identical ? "Identical" : "Different")}"); } } // Close all documents pdfs.ForEach(pdf => pdf.Dispose()); } Imports System Imports System.Collections.Generic Public Shared Sub CompareMultiplePdfs(ParamArray pdfPaths As String()) If pdfPaths.Length < 2 Then Console.WriteLine("Need at least two files to compare") Return End If ' Load multiple PDF documents Dim pdfs As New List(Of PdfDocument)() For Each path As String In pdfPaths pdfs.Add(PdfDocument.FromFile(path)) Next ' Compare all documents For i As Integer = 0 To pdfs.Count - 2 For j As Integer = i + 1 To pdfs.Count - 1 Dim text1 As String = pdfs(i).ExtractAllText() Dim text2 As String = pdfs(j).ExtractAllText() Dim identical As Boolean = text1 = text2 Console.WriteLine($"File {i + 1} vs File {j + 1}: {(If(identical, "Identical", "Different"))}") Next Next ' Close all documents pdfs.ForEach(Sub(pdf) pdf.Dispose()) End Sub $vbLabelText $csharpLabel 這種方法可以在一次運行中比較多個 PDF 文檔,對於批量處理需求非常有用。 輸出 如何使用 IronPDF 和 C# 比較兩個 PDF 檔案:圖 8 - 多個 PDF 輸出 實際合約版本控制 以下是一個追蹤法律文件修訂情況的實用範例: public class ContractVersionControl { public static void CompareContractVersions(string originalPath, string revisedPath) { // System for comparing contract versions Console.WriteLine("Contract Version Comparison System"); var original = PdfDocument.FromFile(originalPath); var revised = PdfDocument.FromFile(revisedPath); // Extract contract contents string originalText = original.ExtractAllText(); string revisedText = revised.ExtractAllText(); if (originalText == revisedText) { Console.WriteLine("No changes detected"); } else { Console.WriteLine("Changes detected in revised version"); // Create detailed report string reportPath = $"contract_comparison_{DateTime.Now:yyyyMMdd}.pdf"; CreateComparisonReport(originalPath, revisedPath, reportPath); Console.WriteLine($"Report created: {reportPath}"); } // Close documents original.Dispose(); revised.Dispose(); } } public class ContractVersionControl { public static void CompareContractVersions(string originalPath, string revisedPath) { // System for comparing contract versions Console.WriteLine("Contract Version Comparison System"); var original = PdfDocument.FromFile(originalPath); var revised = PdfDocument.FromFile(revisedPath); // Extract contract contents string originalText = original.ExtractAllText(); string revisedText = revised.ExtractAllText(); if (originalText == revisedText) { Console.WriteLine("No changes detected"); } else { Console.WriteLine("Changes detected in revised version"); // Create detailed report string reportPath = $"contract_comparison_{DateTime.Now:yyyyMMdd}.pdf"; CreateComparisonReport(originalPath, revisedPath, reportPath); Console.WriteLine($"Report created: {reportPath}"); } // Close documents original.Dispose(); revised.Dispose(); } } Public Class ContractVersionControl Public Shared Sub CompareContractVersions(originalPath As String, revisedPath As String) ' System for comparing contract versions Console.WriteLine("Contract Version Comparison System") Dim original = PdfDocument.FromFile(originalPath) Dim revised = PdfDocument.FromFile(revisedPath) ' Extract contract contents Dim originalText As String = original.ExtractAllText() Dim revisedText As String = revised.ExtractAllText() If originalText = revisedText Then Console.WriteLine("No changes detected") Else Console.WriteLine("Changes detected in revised version") ' Create detailed report Dim reportPath As String = $"contract_comparison_{DateTime.Now:yyyyMMdd}.pdf" CreateComparisonReport(originalPath, revisedPath, reportPath) Console.WriteLine($"Report created: {reportPath}") End If ' Close documents original.Dispose() revised.Dispose() End Sub End Class $vbLabelText $csharpLabel 本範例示範如何比較兩個 PDF 合約版本並產生報告以供審核。 系統會自動偵測變更並產生文件。 處理受密碼保護的PDF文件 IronPDF 透過在呼叫 load 方法時傳遞密碼,可以無縫處理加密的 PDF 檔案: public static bool CompareProtectedPdfs(string pdf1Path, string pass1, string pdf2Path, string pass2) { // Load password-protected two PDFs var pdf1 = PdfDocument.FromFile(pdf1Path, pass1); var pdf2 = PdfDocument.FromFile(pdf2Path, pass2); // Extract and compare text string text1 = pdf1.ExtractAllText(); string text2 = pdf2.ExtractAllText(); bool result = text1 == text2; // Close and dispose pdf1.Dispose(); pdf2.Dispose(); return result; } public static bool CompareProtectedPdfs(string pdf1Path, string pass1, string pdf2Path, string pass2) { // Load password-protected two PDFs var pdf1 = PdfDocument.FromFile(pdf1Path, pass1); var pdf2 = PdfDocument.FromFile(pdf2Path, pass2); // Extract and compare text string text1 = pdf1.ExtractAllText(); string text2 = pdf2.ExtractAllText(); bool result = text1 == text2; // Close and dispose pdf1.Dispose(); pdf2.Dispose(); return result; } Public Shared Function CompareProtectedPdfs(pdf1Path As String, pass1 As String, pdf2Path As String, pass2 As String) As Boolean ' Load password-protected two PDFs Dim pdf1 = PdfDocument.FromFile(pdf1Path, pass1) Dim pdf2 = PdfDocument.FromFile(pdf2Path, pass2) ' Extract and compare text Dim text1 As String = pdf1.ExtractAllText() Dim text2 As String = pdf2.ExtractAllText() Dim result As Boolean = text1 = text2 ' Close and dispose pdf1.Dispose() pdf2.Dispose() Return result End Function $vbLabelText $csharpLabel 載入受保護的PDF檔案時,只需傳遞密碼參數即可。 IronPDF會自動處理解密操作。 輸入 如何使用 IronPDF 和 C# 比較兩個 PDF 檔案:圖 9 - 受保護的 PDF 1 如何使用 IronPDF 和 C# 比較兩個 PDF 檔案:圖 10 - 受保護的 PDF 2 輸出 如何使用 IronPDF 和 C# 比較兩個 PDF 檔案:圖 11 - 受密碼保護的 PDF 輸出 逐步說明 請依照以下步驟在您的 .NET 專案中實作 PDF 比較: 透過 NuGet 安裝 IronPDF for .NET 套件 新增 IronPDF 命名空間引用 為每個檔案建立一個PdfDocument實例 使用ExtractAllText()等方法取得內容 對比提取的文字或實作自訂邏輯 根據需要儲存結果或產生報告 關閉文件物件以釋放資源 如何使用 IronPDF 透過 C# 比較兩個 PDF 檔案:圖 12 - 跨平台相容性 設定您的許可證 若要使用無浮水印的 IronPDF,請設定您的許可證密鑰: IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY"; IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY"; IronPdf.License.LicenseKey = "YOUR-LICENSE-KEY" $vbLabelText $csharpLabel 請造訪許可頁面以了解可用選項的詳細資訊。 下載 IronPDF 的免費試用版,並使用專業級的比較功能設定 PDF 檔案。 如何使用 IronPDF 透過 C# 比較兩個 PDF 檔案:圖 13 - 許可 最佳實務 如果使用追蹤變更功能,請在進行比較之前接受所有修改。 為關鍵文件操作開發錯誤處理機制 透過為大型文件建立頁面特定的比較來提高效能 對多個 PDF 文件非同步運行比較 定期更新您的庫以獲取最新功能和支持 如何使用 IronPDF 和 C# 比較兩個 PDF 檔案:圖 14 - 使用 C# 比較兩個 PDF 檔案 - IronPDF 結論 IronPDF 憑藉其直覺的 API 和強大的提取功能,簡化了使用 C# 比較兩個 PDF 文件的過程。 從基本比較到建立詳細報告,IronPDF 提供了強大的文件比較工作流程所需的所有工具。 IronPDF 具有安裝簡單、功能全面、支援跨平台等優點,是 .NET 應用程式中實現 PDF 比較的開發人員的理想選擇。 無論您是開發文件管理系統還是版本控制解決方案,IronPDF 的簡單方法都能讓您快速上手。 立即開始 IronPDF 的免費試用,體驗專業的 PDF 比較功能。 憑藉全面的技術支援和詳盡的文檔,您將在數小時內獲得可用於生產環境的功能。 請參閱完整文件以了解更多進階功能。 常見問題解答 什麼是 IronPDF,它如何協助比較 PDF 檔案? IronPDF 是一個 .NET 函式庫,提供處理 PDF 檔案的工具,包括以程式化方式比較兩個 PDF 文件的內容或結構差異的功能。 IronPDF 能否突出顯示兩個 PDF 檔案之間的差異? 是的,IronPDF 可透過比較兩個 PDF 檔案的內容來突顯其差異,並提供詳細的變更或差異報告。 使用 IronPDF 比较 PDF 是否需要高级 C# 技能? 不,您不需要高級的 C# 技能。IronPDF 提供簡單直觀的 PDF 檔案比較方法,讓不同技術水準的開發人員都能使用。 是否可以使用 IronPDF 比較加密的 PDF 檔案? 是的,IronPDF 支援比較加密的 PDF 檔案,只要提供正確的密碼即可存取文件內容。 IronPDF 可以檢測兩個 PDF 之間哪些類型的差異? IronPDF 可以檢測出一系列的差異,包括文字變更、圖片修改,以及結構上的改變,例如版面或格式上的改變。 IronPDF 可以整合到現有的 C# 應用程式中嗎? 是的,IronPDF 可輕鬆整合至現有的 C# 應用程式中,讓開發人員無需大幅修改程式碼即可新增 PDF 比較功能。 IronPDF 是否與其他 .NET 應用程式相容? IronPDF 的設計與所有 .NET 應用程式相容,為在 .NET Framework 內工作的開發人員提供無縫的體驗。 IronPDF 是否支援多個 PDF 檔案的批次比對? 是的,IronPDF 支援批次處理,讓開發人員可以在單一作業中比較多個 PDF 檔案,這對於處理大量文件非常有用。 IronPDF 如何確保 PDF 比較的準確性? IronPdf 使用先進的演算法來確保準確且可靠的比對,分析文字和視覺元素以找出任何差異。 開始使用 IronPDF 進行 C# PDF 比對的第一步是什麼? 第一步是在您的 C# 開發環境中透過 NuGet Package Manager 安裝 IronPDF 函式庫,它提供了開始比較 PDF 的所有必要工具。 Curtis Chau 立即與工程團隊聊天 技術撰稿人 Curtis Chau 擁有電腦科學學士學位(卡爾頓大學),專長於前端開發,精通 Node.js、TypeScript、JavaScript 和 React。Curtis 對製作直覺且美觀的使用者介面充滿熱情,他喜歡使用現代化的架構,並製作結構良好且視覺上吸引人的手冊。除了開發之外,Curtis 對物聯網 (IoT) 也有濃厚的興趣,他喜歡探索整合硬體與軟體的創新方式。在空閒時間,他喜歡玩遊戲和建立 Discord bots,將他對技術的熱愛與創意結合。 相關文章 更新2026年1月22日 How to Create PDF Documents in .NET with IronPDF: Complete Guide Discover effective methods to create PDF files in C# for developers. Enhance your coding skills and streamline your projects. Read the article now! 閱讀更多 更新2026年1月21日 How to Merge PDF Files in VB.NET: Complete Tutorial Merge PDF VB NET with IronPDF. Learn to combine multiple PDF files into one document using simple VB.NET code. Step-by-step examples included. 閱讀更多 更新2026年1月21日 C# PDFWriter Tutorial: Create PDF Documents in .NET Learn to create PDFs efficiently using C# PDFWriter with this step-by-step guide for developers. Read the article to enhance your skills today! 閱讀更多 How to Convert a PDF to an Image in .NETHow to Create PDF Files in .NET Core
更新2026年1月22日 How to Create PDF Documents in .NET with IronPDF: Complete Guide Discover effective methods to create PDF files in C# for developers. Enhance your coding skills and streamline your projects. Read the article now! 閱讀更多
更新2026年1月21日 How to Merge PDF Files in VB.NET: Complete Tutorial Merge PDF VB NET with IronPDF. Learn to combine multiple PDF files into one document using simple VB.NET code. Step-by-step examples included. 閱讀更多
更新2026年1月21日 C# PDFWriter Tutorial: Create PDF Documents in .NET Learn to create PDFs efficiently using C# PDFWriter with this step-by-step guide for developers. Read the article to enhance your skills today! 閱讀更多