我正在开发一个 C# 应用程序,其中我将 PDF 文档转换为图像,然后在自定义查看器中呈现该图像。
在尝试在生成的图像中搜索特定单词时,我遇到了一些障碍,我想知道最好的方法是什么。我应该找到搜索词的 x,y 位置吗?
您可以在控制台模式下使用tessract OCR 图像进行文本识别。
我不知道这种用于pdf的SDK。
但是,如果你想获取所有单词的坐标和值,你可以使用下一个我不复杂的代码,感谢nguyenq的 hocr 提示:
public void Recognize(Bitmap bitmap)
{
bitmap.Save("temp.png", ImageFormat.Png);
var startInfo = new ProcessStartInfo("tesseract.exe", "temp.png temp hocr");
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
var process = Process.Start(startInfo);
process.WaitForExit();
GetWords(File.ReadAllText("temp.html"));
// Futher actions with words
}
public Dictionary<Rectangle, string> GetWords(string tesseractHtml)
{
var xml = XDocument.Parse(tesseractHtml);
var rectsWords = new Dictionary<System.Drawing.Rectangle, string>();
var ocr_words = xml.Descendants("span").Where(element => element.Attribute("class").Value == "ocr_word").ToList();
foreach (var ocr_word in ocr_words)
{
var strs = ocr_word.Attribute("title").Value.Split(' ');
int left = int.Parse(strs[1]);
int top = int.Parse(strs[2]);
int width = int.Parse(strs[3]) - left + 1;
int height = int.Parse(strs[4]) - top + 1;
rectsWords.Add(new Rectangle(left, top, width, height), ocr_word.Value);
}
return rectsWords;
}
使用 ITextSharp在此处下载。确保 PDF 是可搜索的。
并使用此代码:
public static string GetTextFromAllPages(String pdfPath)
{
PdfReader reader = new PdfReader(pdfPath);
StringWriter output = new StringWriter();
for (int i = 1; i <= reader.NumberOfPages; i++)
output.WriteLine(PdfTextExtractor.GetTextFromPage(reader, i, new SimpleTextExtractionStrategy()));
return output.ToString();
}