【问题标题】:How to extract text from a PDF and decode characters?如何从 PDF 中提取文本并解码字符?
【发布时间】:2012-12-20 16:15:57
【问题描述】:

我正在使用 itextsharp 使用以下代码从 pdf 文档中提取文本:

public static bool does_document_text_have_keyword(string keyword, 
                       string pdf_src, Report report_object)  // TEST
{
    try
    {
        PdfReader pdfReader = new PdfReader(pdf_src);
        string currentText;
        int count = pdfReader.NumberOfPages;
        for (int page = 1; page <= count; page++)
        {
           ITextExtractionStrategy strategy = new SimpleTextExtractionStrategy();
           currentText = PdfTextExtractor.GetTextFromPage
                           (pdfReader, page, strategy);
           currentText = Encoding.UTF8.GetString
                           (ASCIIEncoding.Convert
                             (Encoding.Default,                                 
                              Encoding.UTF8, 
                              Encoding.Default.GetBytes(currentText)));

           report_object.log(currentText);  // TEST

           if (currentText.IndexOf
                (keyword, StringComparison.OrdinalIgnoreCase) != -1) return true;
        }
        pdfReader.Close();
        return false;
    }
    catch
    {
        return false;
    }
}

但问题是,当我提取文本时,文本没有空格,就好像空格被替换为空字符串一样。然而在pdf文档中,里面有空格。有谁知道这里发生了什么?

【问题讨论】:

  • 在致电PdfTextExtractor.GetTextFromPage(pdfReader, page, strategy) 之后,您在currentText 中有什么?
  • @cheesemacfly,结果一样
  • @ray cheng,我需要空格,因为我提取文本来搜索单词
  • 这个解决方案怎么样:stackoverflow.com/a/8448889/1443490
  • 此外,如需确定性建议,请提供说明问题的示例文件。

标签: c# pdf itextsharp


【解决方案1】:

我相信您的问题是 SimpleTextExtractionStrategy。来自http://api.itextpdf.com/itext/com/itextpdf/text/pdf/parser/SimpleTextExtractionStrategy.html的 API 文档

如果 PDF 以非从上到下的方式呈现文本,这将导致文本无法真实表示它在 PDF 中的显示方式。此渲染器还使用基于字体度量的简单策略来确定是否应在输出中插入空格。

尝试使用 LocationTextExtractionStrategy。它的文档指出:

跟踪文本在页面上的相对位置的文本提取渲染器生成的文本将与大多数 PDF 文件在屏幕上的物理布局相对一致。

【讨论】:

  • 虽然LocationTextExtractionStrategy 通常不太依赖于出现在页面内容中的文本片段的顺序,但SimpleTextExtractionStrategy 在这里不太可能有问题。对于同一行中的单词,它们使用非常相似的机制来确定中间是否有空格。
猜你喜欢
  • 2019-12-05
  • 2023-04-02
  • 2020-01-21
  • 2012-07-20
  • 2016-04-22
  • 2012-08-24
  • 1970-01-01
  • 2015-08-17
相关资源
最近更新 更多