從緊密排列的表中提取不按順序的文字
從緊密排列的表或表單佈局中提取的文字顯得混亂。 鄰近行的字元交錯,例如"Unique Number 123456789"被提取為"U123456789nique Number"。
這是page.Lines提取密集佈局的一個已知限制。 page.Lines通過內建的不可配置的垂直容差來分組字元。 當表格單元格中兩行可見行只有一兩點距離時,分組器將兩行合併為一條邏輯線,並從左至右排序字元,將它們交錯排列。 ExtractTextFromPage(i)方法預設為內容流順序,這可能與表單PDF中的視覺閱讀順序不一致。
解決方案
建議:使用可調節容差的TextChunks提取
每個BoundingBox,允許按垂直位置分組,並在每行內按水平位置排序:
using IronPdf.Pages;
using System.Text;
static string ExtractTextUsingTextChunks(IPdfPage page, double rowTolerance = 2.0)
{
var rows = page.TextChunks
.Where(c => !string.IsNullOrWhiteSpace(c.Contents))
.GroupBy(c => Math.Round(c.BoundingBox.Top / rowTolerance) * rowTolerance)
.OrderByDescending(g => g.Key);
var extractedText = new StringBuilder();
foreach (var row in rows)
{
var line = string.Join(" ",
row.OrderBy(c => c.BoundingBox.Left)
.Select(c => c.Contents.Trim())
.Where(text => !string.IsNullOrWhiteSpace(text)));
extractedText.AppendLine(line);
}
return extractedText.ToString();
}
using IronPdf.Pages;
using System.Text;
static string ExtractTextUsingTextChunks(IPdfPage page, double rowTolerance = 2.0)
{
var rows = page.TextChunks
.Where(c => !string.IsNullOrWhiteSpace(c.Contents))
.GroupBy(c => Math.Round(c.BoundingBox.Top / rowTolerance) * rowTolerance)
.OrderByDescending(g => g.Key);
var extractedText = new StringBuilder();
foreach (var row in rows)
{
var line = string.Join(" ",
row.OrderBy(c => c.BoundingBox.Left)
.Select(c => c.Contents.Trim())
.Where(text => !string.IsNullOrWhiteSpace(text)));
extractedText.AppendLine(line);
}
return extractedText.ToString();
}
Imports IronPdf.Pages
Imports System.Text
Private Shared Function ExtractTextUsingTextChunks(page As IPdfPage, Optional rowTolerance As Double = 2.0) As String
Dim rows = page.TextChunks _
.Where(Function(c) Not String.IsNullOrWhiteSpace(c.Contents)) _
.GroupBy(Function(c) Math.Round(c.BoundingBox.Top / rowTolerance) * rowTolerance) _
.OrderByDescending(Function(g) g.Key)
Dim extractedText As New StringBuilder()
For Each row In rows
Dim line = String.Join(" ", row.OrderBy(Function(c) c.BoundingBox.Left) _
.Select(Function(c) c.Contents.Trim()) _
.Where(Function(text) Not String.IsNullOrWhiteSpace(text)))
extractedText.AppendLine(line)
Next
Return extractedText.ToString()
End Function
從rowTolerance = 2.0開始。 如果行仍然合併,將其降低到0.5。 為更精細的控制,將page.TextChunks。
替代方案:視覺順序提取
對於只有內容流順序錯誤的PDF:
pdf.ExtractTextFromPage(i, TextExtractionOrder.VisualOrder);
pdf.ExtractTextFromPage(i, TextExtractionOrder.VisualOrder);
pdf.ExtractTextFromPage(i, TextExtractionOrder.VisualOrder)
對於行在視覺上非常接近的PDF,TextChunks方法能更好地處理緊密容差。

