Windows Forms文本框中的OCR换行
Curtis Chau
更新: 2026年8月21日
使用IronOCR提取的OCR文本在显示在Windows Forms TextBox中时,可能会丢失换行符。 引擎返回换行符 (\n),但Windows需要回车符加换行符 (\r\n) 才能换行,所以文本呈现为一个连续的块。
解决方案
1. 在64位模式下使用AdvancedScan
参考IronOCR.Extensions.AdvancedScan包以获得更强的OCR功能,并在64位模式下运行应用程序以避免兼容性问题。
2. 规范化OCR输出中的换行符
在将结果分配给TextBox之前,将每个\n替换为\r\n。 这为Windows提供了所需的回车/换行组合。
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 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 Usingocr.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 Usingresult.Text.Replace("\n", "\r\n")进行转换; 其余部分加载图像,校正倾斜,并读取截图。
3. 测试和验证
再次运行提取并确认TextBox内容与原始布局匹配,包括换行符。
原始图像:

前:

后:

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