我正在尝试使用 iTextSharp 库将 PDF 中的文本读入字符串。
iTextSharp.text.pdf.PdfReader pdfReader = new iTextSharp.text.pdf.PdfReader(@"C:\mypdf.pdf");
ITextExtractionStrategy strategy = new SimpleTextExtractionStrategy();
string currentText = PdfTextExtractor.GetTextFromPage(pdfReader, 1, strategy);
text = Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(currentText)));
pdfReader.Close();
Console.WriteLine(text);
这通常工作正常,但每隔几行空格就会被省略,给我留下这样的输出:“thisismyoutputwithoutwhitespace”。正确解析的文本似乎与未正确解析的文本相同;相同的文本将始终被错误地解析,这让我认为这是 PDF 中的某些内容。
最佳答案
在 PDF 的内容流中,没有“单词”的概念。所以在 iText(Sharp) 的文本提取实现中,有一些启发式方法来确定如何将字符分组为单词。当两个字符之间的距离大于当前字体中空格宽度的一半时,将插入空格。
最有可能的是,在没有空格的情况下提取的文本在单词之间的距离小于“spacewidth/2”。
在 SimpleTextExtractionStrategy.RenderText()
中:
if (spacing > renderInfo.GetSingleSpaceWidth()/2f){
AppendTextChunk(' ');
}
您可以扩展 SimpleTextExtractionStrategy
并调整 RenderText()
。
在LocationTextExtractionStrategy
中更方便。你只需要重写IsChunkAtWordBoundary()
:
protected bool IsChunkAtWordBoundary(TextChunk chunk, TextChunk previousChunk) {
float dist = chunk.DistanceFromEndOf(previousChunk);
if(dist < -chunk.CharSpaceWidth || dist > chunk.CharSpaceWidth / 2.0f)
return true;
return false;
}
您需要进行一些试验才能获得良好的 PDF 效果。 "spacewidth/2"在你的情况下显然太大了。但如果将其调整得太小,就会出现误报:单词中会插入空格。
关于c# - 在 .NET 中从 PDF 中读取文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20523524/