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针对下面这样的源图像运行:

将原始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内容与源图像进行比较。 换行现在应该与原始布局对齐。

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

