Windows Forms TextBox中的不正确换行

This article was translated from English: Does it need improvement?
Translated
View the article in English

使用IronOCR提取的OCR文本在Windows Forms TextBox显示时可能丢失其换行,导致其比源图像线更少。

原因是换行符不匹配。 IronOCR返回的换行是裸换行符(\n),但Windows Forms \r\n)时才渲染换行。 没有回车符,控件会忽略换行。

OCR针对下面这样的源图像运行:

向IronOCR传递以提取文本的源图像

将原始OCR结果直接绑定到控件会将文本折叠到几行,而不是保留原始布局:

Windows Forms应用程序显示OCR文本,换行合并为两行

解决方案

1. 在64位模式下使用AdvancedScan

安装IronOcr.Extensions.AdvancedScan包以获得更可靠的提取,并在64位模式下运行应用程序以避免兼容性问题。

<PackageReference Include="IronOcr.Extensions.AdvancedScan" />
<PackageReference Include="IronOcr.Extensions.AdvancedScan" />
XML

2. 正规化行结束符

在将文本分配给控件之前,将结果中的每个\r\n

ocr.Language = OcrLanguage.ChineseSimplifiedBest;
using (var ocrInput = new OcrInput())
{
    ocrInput.LoadImage(txtPath.Text);
    ocrInput.Deskew();
    var result = ocr.ReadScreenShot(ocrInput);
    // Replace line feed with carriage return and line feed
    string ocrText = result.Text.Replace("\n", "\r\n");
    // Display the corrected text in a TextBox
    textBox1.Text = ocrText;
}
ocr.Language = OcrLanguage.ChineseSimplifiedBest;
using (var ocrInput = new OcrInput())
{
    ocrInput.LoadImage(txtPath.Text);
    ocrInput.Deskew();
    var result = ocr.ReadScreenShot(ocrInput);
    // Replace line feed with carriage return and line feed
    string ocrText = result.Text.Replace("\n", "\r\n");
    // Display the corrected text in a TextBox
    textBox1.Text = ocrText;
}
Imports System

ocr.Language = OcrLanguage.ChineseSimplifiedBest
Using ocrInput As New OcrInput()
    ocrInput.LoadImage(txtPath.Text)
    ocrInput.Deskew()
    Dim result = ocr.ReadScreenShot(ocrInput)
    ' Replace line feed with carriage return and line feed
    Dim ocrText As String = result.Text.Replace(vbLf, vbCrLf)
    ' Display the corrected text in a TextBox
    textBox1.Text = ocrText
End Using
$vbLabelText   $csharpLabel

TextBox所期望的回车/换行符对,因此显示的文本保持与原始图像相同的行结构。

3. 验证输出

再次运行提取并将TextBox内容与源图像进行比较。 换行现在应该与原始布局对齐。

Windows Forms应用程序显示OCR文本,其换行正确保留

Curtis Chau
技术作家

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

除了开发之外,Curtis 对物联网 (IoT) 有浓厚的兴趣,探索将硬件和软件集成的新方法。在空闲时间,他喜欢玩游戏和构建 Discord 机器人,将他对技术的热爱与创造力相结合。

准备开始了吗?
Nuget 下载 6,136,090 | 版本: 2026.7 刚刚发布
Still Scrolling Icon

还在滚动吗?

想快速获得证据? PM > Install-Package IronOcr
运行示例 观看您的图像变成可搜索文本。