簡體   English   中英

如何從pdf圖像中查找文本?

[英]How to find text from pdf image?

我正在開發一個C#應用程序,我將PDF文檔轉換為圖像,然后在自定義查看器中呈現該圖像。

在嘗試搜索生成的圖像中的特定單詞時,我遇到了一些磚牆,我想知道最好的方法是什么。 我應該找到搜索到的單詞的x,y位置嗎?

您可以在控制台模式下使用tessract OCR圖像進行文本識別。

我不知道這樣的pdf SDK。

但是,如果你想獲得所有的單詞坐標和值,你可以使用下一個我不復雜的代碼,感謝nguyenq for 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();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM