如何使用 IronOCR 在 C# 中进行进度跟踪
IronOCR提供基于事件的进度跟踪系统用于OCR操作,允许开发人员通过OcrProgress事件实时监测读取进度,报告完成百分比、已处理页面和时间指标。
本例显示了如何使用IronOCR监控OCR进度:订阅其内置的OcrProgress事件,并接收即时反馈,包括百分比、已完成页面数和总页面数,同时读取PDF。 只需几行即可开始。
-
1Install IronOCR with NuGet Package Manager
-
2复制并运行这段代码。
var ocr = new IronOcr.IronTesseract(); ocr.OcrProgress += (s, e) => Console.WriteLine(e.ProgressPercent + "% (" + e.PagesComplete + "/" + e.TotalPages + ")"); var result = ocr.Read(new IronOcr.OcrInput().LoadPdf("file.pdf"));C# -
3部署到您的生产环境中进行测试
通过免费试用立即在您的项目中开始使用IronOCR
最小工作流程(5 个步骤)
- 下载一个用于跟踪阅读进度的 C# 库
- 订阅OcrProgress活动
- 利用事件传递的实例获取进度信息
- 以百分比和总时间获取进度
- 获取开始时间和结束时间,以及总页数
如何在我的 OCR 应用程序中实施进度跟踪?
在使用 OCR 处理大型文档或批量文件时,进度跟踪至关重要。 OcrProgress事件可以订阅以接收阅读过程的进度更新。 这对于PDF OCR 操作和处理多页 TIFF 文件尤其有用。
该事件传递一个包含 OCR 作业进度信息的实例,如开始时间、总页数、进度百分比、持续时间和结束时间。该功能可与 async 操作无缝配合,并可与 multithreading 结合使用以提高性能。
下面的示例以该文档为样本:"生物多样性研究经验:"作者:Thea B. 盖斯勒,爱荷华州立大学。
using IronOcr;
using System;
var ocrTesseract = new IronTesseract();
// Subscribe to OcrProgress event
ocrTesseract.OcrProgress += (_, ocrProgressEventsArgs) =>
{
Console.WriteLine("Start time: " + ocrProgressEventsArgs.StartTimeUTC.ToString());
Console.WriteLine("Total pages number: " + ocrProgressEventsArgs.TotalPages);
Console.WriteLine("Progress(%) | Duration");
Console.WriteLine(" " + ocrProgressEventsArgs.ProgressPercent + "% | " + ocrProgressEventsArgs.Duration.TotalSeconds + "s");
Console.WriteLine("End time: " + ocrProgressEventsArgs.EndTimeUTC.ToString());
Console.WriteLine("----------------------------------------------");
};
using var input = new OcrInput();
input.LoadPdf("Experiences-in-Biodiversity-Research-A-Field-Course.pdf");
// Progress events will fire during the read operation
var result = ocrTesseract.Read(input);Imports IronOcr
Imports System
Private ocrTesseract = New IronTesseract()
' Subscribe to OcrProgress event
Private ocrTesseract.OcrProgress += Sub(underscore, ocrProgressEventsArgs)
Console.WriteLine("Start time: " & ocrProgressEventsArgs.StartTimeUTC.ToString())
Console.WriteLine("Total pages number: " & ocrProgressEventsArgs.TotalPages)
Console.WriteLine("Progress(%) | Duration")
Console.WriteLine(" " & ocrProgressEventsArgs.ProgressPercent & "% | " & ocrProgressEventsArgs.Duration.TotalSeconds & "s")
Console.WriteLine("End time: " & ocrProgressEventsArgs.EndTimeUTC.ToString())
Console.WriteLine("----------------------------------------------")
End Sub
Private input = New OcrInput()
input.LoadPdf("Experiences-in-Biodiversity-Research-A-Field-Course.pdf")
' Progress events will fire during the read operation
Dim result = ocrTesseract.Read(input)我可以从活动中获取哪些进度信息?
OcrProgress事件提供全面的进度数据,有助于监控和优化OCR性能。 每个属性在跟踪操作中都有特定的用途:
ProgressPercent:OCR工作进度,完成页数的百分比,范围从0到100。适用于在GUI应用程序中更新进度条。TotalPages:OCR引擎正在处理的页面总数。对计算预计完成时间至关重要。PagesComplete:OCR读取已全面完成的页面数。 随着页面的处理,翻译量会逐渐增加。Duration:OCR工作的总时长,指示整个过程完成的所需时间。 以TimeSpan格式测量,并在每次触发事件时更新。StartTimeUTC:OCR作业启动的日期和时间,以协调世界时(UTC)格式表示。EndTimeUTC:OCR作业100%完成的日期和时间,以UTC格式表示。 当 OCR 正在进行时,该属性为空,而一旦该过程结束,该属性就会被填充。
高级进度跟踪实施
对于生产应用程序,实施更复杂的进度跟踪。 本示例包括错误处理和详细日志记录:
using IronOcr;
using System;
using System.Diagnostics;
public class OcrProgressTracker
{
private readonly IronTesseract _tesseract;
private Stopwatch _stopwatch;
private int _lastReportedPercent = 0;
public OcrProgressTracker()
{
_tesseract = new IronTesseract();
// Configure for optimal performance
_tesseract.Language = OcrLanguage.EnglishBest;
_tesseract.Configuration.ReadBarCodes = false;
// Subscribe to progress event
_tesseract.OcrProgress += OnOcrProgress;
}
private void OnOcrProgress(object sender, OcrProgressEventsArgs e)
{
// Only report significant progress changes (every 10%)
if (e.ProgressPercent - _lastReportedPercent >= 10 || e.ProgressPercent == 100)
{
_lastReportedPercent = e.ProgressPercent;
Console.WriteLine($"Progress: {e.ProgressPercent}%");
Console.WriteLine($"Pages: {e.PagesComplete}/{e.TotalPages}");
Console.WriteLine($"Elapsed: {e.Duration.TotalSeconds:F1}s");
// Estimate remaining time
if (e.ProgressPercent > 0 && e.ProgressPercent < 100)
{
var estimatedTotal = e.Duration.TotalSeconds / (e.ProgressPercent / 100.0);
var remaining = estimatedTotal - e.Duration.TotalSeconds;
Console.WriteLine($"Estimated remaining: {remaining:F1}s");
}
Console.WriteLine("---");
}
}
public OcrResult ProcessDocument(string filePath)
{
_stopwatch = Stopwatch.StartNew();
using var input = new OcrInput();
input.LoadPdf(filePath);
// Apply image filters for better accuracy
input.Deskew();
input.DeNoise();
var result = _tesseract.Read(input);
_stopwatch.Stop();
Console.WriteLine($"Total processing time: {_stopwatch.Elapsed.TotalSeconds:F1}s");
return result;
}
}Imports IronOcr
Imports System
Imports System.Diagnostics
Public Class OcrProgressTracker
Private ReadOnly _tesseract As IronTesseract
Private _stopwatch As Stopwatch
Private _lastReportedPercent As Integer = 0
Public Sub New()
_tesseract = New IronTesseract()
' Configure for optimal performance
_tesseract.Language = OcrLanguage.EnglishBest
_tesseract.Configuration.ReadBarCodes = False
' Subscribe to progress event
AddHandler _tesseract.OcrProgress, AddressOf OnOcrProgress
End Sub
Private Sub OnOcrProgress(sender As Object, e As OcrProgressEventsArgs)
' Only report significant progress changes (every 10%)
If e.ProgressPercent - _lastReportedPercent >= 10 OrElse e.ProgressPercent = 100 Then
_lastReportedPercent = e.ProgressPercent
Console.WriteLine($"Progress: {e.ProgressPercent}%")
Console.WriteLine($"Pages: {e.PagesComplete}/{e.TotalPages}")
Console.WriteLine($"Elapsed: {e.Duration.TotalSeconds:F1}s")
' Estimate remaining time
If e.ProgressPercent > 0 AndAlso e.ProgressPercent < 100 Then
Dim estimatedTotal = e.Duration.TotalSeconds / (e.ProgressPercent / 100.0)
Dim remaining = estimatedTotal - e.Duration.TotalSeconds
Console.WriteLine($"Estimated remaining: {remaining:F1}s")
End If
Console.WriteLine("---")
End If
End Sub
Public Function ProcessDocument(filePath As String) As OcrResult
_stopwatch = Stopwatch.StartNew()
Using input As New OcrInput()
input.LoadPdf(filePath)
' Apply image filters for better accuracy
input.Deskew()
input.DeNoise()
Dim result = _tesseract.Read(input)
_stopwatch.Stop()
Console.WriteLine($"Total processing time: {_stopwatch.Elapsed.TotalSeconds:F1}s")
Return result
End Using
End Function
End Class将进度跟踪与 UI 应用程序相结合
在使用 Windows 窗体或 WPF 构建桌面应用程序时,进度跟踪对用户体验至关重要。 进度事件可以安全地更新 UI 元素:
using System;
using System.Windows.Forms;
using IronOcr;
public partial class OcrForm : Form
{
private IronTesseract _tesseract;
private ProgressBar progressBar;
private Label statusLabel;
public OcrForm()
{
InitializeComponent();
_tesseract = new IronTesseract();
_tesseract.OcrProgress += UpdateProgress;
}
private void UpdateProgress(object sender, OcrProgressEventsArgs e)
{
// Ensure UI updates happen on the main thread
if (InvokeRequired)
{
BeginInvoke(new Action(() => UpdateProgress(sender, e)));
return;
}
progressBar.Value = e.ProgressPercent;
statusLabel.Text = $"Processing page {e.PagesComplete} of {e.TotalPages}";
// Show completion message
if (e.ProgressPercent == 100)
{
MessageBox.Show($"OCR completed in {e.Duration.TotalSeconds:F1} seconds");
}
}
}Imports System
Imports System.Windows.Forms
Imports IronOcr
Public Partial Class OcrForm
Inherits Form
Private _tesseract As IronTesseract
Private progressBar As ProgressBar
Private statusLabel As Label
Public Sub New()
InitializeComponent()
_tesseract = New IronTesseract()
AddHandler _tesseract.OcrProgress, AddressOf UpdateProgress
End Sub
Private Sub UpdateProgress(sender As Object, e As OcrProgressEventsArgs)
' Ensure UI updates happen on the main thread
If InvokeRequired Then
BeginInvoke(New Action(Sub() UpdateProgress(sender, e)))
Return
End If
progressBar.Value = e.ProgressPercent
statusLabel.Text = $"Processing page {e.PagesComplete} of {e.TotalPages}"
' Show completion message
If e.ProgressPercent = 100 Then
MessageBox.Show($"OCR completed in {e.Duration.TotalSeconds:F1} seconds")
End If
End Sub
End Class处理大型文档和超时
在处理大量文件时,进度跟踪变得更加重要。 将其与超时设置和中止令牌相结合,可实现更好的控制:
using IronOcr;
using System;
using System.Threading;
public async Task ProcessLargeDocumentWithTimeout()
{
var cts = new CancellationTokenSource();
var tesseract = new IronTesseract();
// Set a timeout of 5 minutes
cts.CancelAfter(TimeSpan.FromMinutes(5));
tesseract.OcrProgress += (s, e) =>
{
Console.WriteLine($"Progress: {e.ProgressPercent}% - Page {e.PagesComplete}/{e.TotalPages}");
// Check if we should cancel based on progress
if (e.Duration.TotalMinutes > 4 && e.ProgressPercent < 50)
{
Console.WriteLine("Processing too slow, cancelling...");
cts.Cancel();
}
};
try
{
using var input = new OcrInput();
input.LoadPdf("large-document.pdf");
var result = await Task.Run(() =>
tesseract.Read(input, cts.Token), cts.Token);
Console.WriteLine("OCR completed successfully");
}
catch (OperationCanceledException)
{
Console.WriteLine("OCR operation was cancelled");
}
}Imports IronOcr
Imports System
Imports System.Threading
Public Async Function ProcessLargeDocumentWithTimeout() As Task
Dim cts = New CancellationTokenSource()
Dim tesseract = New IronTesseract()
' Set a timeout of 5 minutes
cts.CancelAfter(TimeSpan.FromMinutes(5))
AddHandler tesseract.OcrProgress, Sub(s, e)
Console.WriteLine($"Progress: {e.ProgressPercent}% - Page {e.PagesComplete}/{e.TotalPages}")
' Check if we should cancel based on progress
If e.Duration.TotalMinutes > 4 AndAlso e.ProgressPercent < 50 Then
Console.WriteLine("Processing too slow, cancelling...")
cts.Cancel()
End If
End Sub
Try
Using input As New OcrInput()
input.LoadPdf("large-document.pdf")
Dim result = Await Task.Run(Function() tesseract.Read(input, cts.Token), cts.Token)
Console.WriteLine("OCR completed successfully")
End Using
Catch ex As OperationCanceledException
Console.WriteLine("OCR operation was cancelled")
End Try
End Function进度跟踪的最佳实践
- 更新频率:
OcrProgress事件经常在处理过程中触发。 考虑过滤更新,以避免 UI 或日志过多。
2.性能影响:进度跟踪的性能开销极小,但过多的日志记录或 UI 更新可能会减慢 OCR 进程。
3.内存管理:对于大型 TIFF 文件或 PDF 文件,应随着进度监控内存使用情况,以确保最佳性能。
4.错误处理:始终在进度事件处理程序中包含错误处理,以防止异常干扰 OCR 进程。
- 线程安全:当从进度事件更新UI元素时,确保使用
BeginInvoke方法进行适当的线程同步。
结论
IronOCR 中的进度跟踪提供了 OCR 操作的基本可见性,使开发人员能够创建响应式应用程序,让用户随时了解处理状态。 通过有效利用OcrProgress事件,您可以自信地构建处理从单页文档到大型PDF文件的专业应用程序。
如需了解更多高级 OCR 技术,请浏览我们的 图像过滤器 和 结果对象 指南,以进一步增强您的 OCR 实现。
常见问题解答
如何实时跟踪 OCR 进度?
IronOCR 通过 OcrProgress 事件提供基于事件的进度跟踪系统。只需在您的 IronTesseract 实例上订阅该事件,您就会收到实时更新,包括 OCR 操作期间的完成百分比、已处理页面和时间指标。
OcrProgress 活动提供哪些信息?
IronOCR 中的 OcrProgress 事件提供了全面的数据,包括 ProgressPercent(0-100%)、TotalPages 计数、PagesComplete 计数、开始和结束时间以及总持续时间。这些信息对于更新 GUI 应用程序中的进度条和监控 OCR 性能特别有用。
我可以在异步 OCR 操作中使用进度跟踪吗?
是的,IronOCR 的进度跟踪功能可与异步操作无缝配合。您可以将其与异步处理甚至多线程结合起来以提高性能,同时还能通过 OcrProgress 事件接收实时进度更新。
如何为 PDF OCR 实现一个简单的进度跟踪器?
要使用 IronOCR 实现基本的进度跟踪,需要创建一个 IronTesseract 实例,使用 lambda 表达式或事件处理程序订阅 OcrProgress 事件,然后调用 PDF 的 Read 方法。该事件将定期触发,提供完成百分比和已处理页数信息。
进度跟踪对大型文档处理有用吗?
在使用 IronOCR 处理大型文档或批量文件时,进度跟踪至关重要。它对于 PDF OCR 操作和多页 TIFF 文件尤为重要,可以让您监控处理状态、估算完成时间,并在长时间的操作过程中提供用户反馈。
Is there a recommended frequency for OcrProgress updates?
While the OcrProgress event fires frequently, it's recommended to filter updates to avoid overwhelming your UI or logs, which can impact performance.
How can IronOCR's progress tracking improve the processing of large documents?
When dealing with large documents, IronOCR's progress tracking allows for better control with timeout settings and abort tokens, providing a mechanism to handle slow processing efficiently.
Does progress tracking in IronOCR affect performance?
Progress tracking in IronOCR has minimal performance overhead, although excessive logging or UI updates based on progress events may slow down the overall OCR process.
What best practices should I follow for using progress tracking in IronOCR?
Best practices include managing update frequencies, ensuring thread safety when updating UI elements, and incorporating error handling to maintain smooth OCR operations.
Can IronOCR be used for tracking progress in multi-threaded environments?
Yes, IronOCR's progress tracking can be combined with multi-threading to enhance OCR performance, handling multiple documents or large files more efficiently.

Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。