【问题标题】:Extract text by line from PDF using iTextSharp c#使用 iTextSharp c# 从 PDF 中逐行提取文本
【发布时间】:2013-04-01 18:00:33
【问题描述】:

我需要对从 PDF 文档中提取的数据进行一些分析。

使用iTextSharp,我使用PdfTextExtractor.GetTextFromPage 方法从PDF 文档中提取内容,它以一行长的形式返回给我。

有没有办法逐行获取文本,以便我可以将它们存储在数组中?这样我就可以逐行分析数据,这将更加灵活。

下面是我使用的代码:

       string urlFileName1 = "pdf_link";
        PdfReader reader = new PdfReader(urlFileName1);
        string text = string.Empty;
        for (int page = 1; page <= reader.NumberOfPages; page++)
        {
            text += PdfTextExtractor.GetTextFromPage(reader, page);
        }
        reader.Close();
        candidate3.Text = text.ToString();

【问题讨论】:

  • Xander 几个问题.. 首先PdfReader(urFileName)` 会在通话期间一次读取所有行吗..?如果是这样,那么您可能需要将 for 循环更改为 while 循环并调用 reader.ReadLine() 方法。我正在寻找如何使用 StreamReader 类正常读取让我知道是否有 .ReadLine() 方法 @987654321 @查看此链接
  • 嗨@DJKRAZE 是的,PdfReader(urlFileName1) 一次读取所有行。我认为 iTextSharp 中没有 .ReadLine() 方法。去了他们的API 并找不到它。你能做一个例子来说明你对while循环的意思吗?
  • 看看这个Previous Stackoverflow 发帖应该指出你正确的方向stackoverflow.com/questions/2550796/…
  • PdfTextExtractor.GetTextFromPage(reader, page) 使用 LocationTextExtractionStrategy 反过来在文本行更改时插入 '\n'。如果它不适合你,那是有问题的。因此,您能否提供 PDF 以供检查?
  • 尝试 text.Replace("\n","
    ")

标签: c# pdf itext extract carriage-return


【解决方案1】:

这里的所有其他代码示例都不适用于我,可能是由于对 itext7 API 的更改。

这个最小的例子在这里工作正常:

var pdfReader = new iText.Kernel.Pdf.PdfReader(fileName);
var pdfDocument = new iText.Kernel.Pdf.PdfDocument(pdfReader);
var contents = iText.Kernel.Pdf.Canvas.Parser.PdfTextExtractor.GetTextFromPage(pdfDocument.GetFirstPage());

【讨论】:

  • GetTextFromPage 有一个重载,允许您也传递 ITextExtractionStrategy。
【解决方案2】:

我知道这是在较早的帖子上发布的,但我花了很多时间试图弄清楚这一点,所以我将与未来尝试谷歌搜索的人分享:

using System;
using System.Text;
using iTextSharp.text.pdf;
using iTextSharp.text.pdf.parser;

namespace PDFApp2
{
class Program
{
    static void Main(string[] args)
    {

        string filePath = @"Your said path\the file name.pdf";
        string outPath = @"the output said path\the text file name.txt";
        int pagesToScan = 2;

        string strText = string.Empty;
        try
        {
            PdfReader reader = new PdfReader(filePath);

            for (int page = 1; page <= pagesToScan; page ++) //(int page = 1; page <= reader.NumberOfPages; page++) <- for scanning all the pages in A PDF
            {
                ITextExtractionStrategy its = new iTextSharp.text.pdf.parser.LocationTextExtractionStrategy();
                strText = PdfTextExtractor.GetTextFromPage(reader, page, its);

                strText = Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(strText)));
                //creating the string array and storing the PDF line by line
                string[] lines = strText.Split('\n');
                foreach (string line in lines)
                {
                    //Creating and appending to a text file
                    using (System.IO.StreamWriter file = new System.IO.StreamWriter(outPath, true))
                    {
                        file.WriteLine(line);
                    }
                }
            }

            reader.Close();
        }
        catch (Exception ex)
        {
            Console.Write(ex);
        }
    }
}
}

我让程序从设置的路径读取 PDF,然后输出到文本文件,但您可以将其操作到任何内容。这是建立在 Snziv Gupta 的回应之上的。

【讨论】:

    【解决方案3】:
        public void ExtractTextFromPdf(string path)
        {
            using (PdfReader reader = new PdfReader(path))
            {
                StringBuilder text = new StringBuilder();
                ITextExtractionStrategy Strategy = new iTextSharp.text.pdf.parser.LocationTextExtractionStrategy();
    
                for (int i = 1; i <= reader.NumberOfPages; i++)
                {
                    string page = "";
    
                    page = PdfTextExtractor.GetTextFromPage(reader, i,Strategy);
                    string[] lines = page.Split('\n');
                    foreach (string line in lines)
                    {
                        MessageBox.Show(line);
                    }
                }
            }
        }
    

    【讨论】:

    • 发布答案时,请务必包含一些关于您的代码如何工作以及它究竟做了什么的摘要。仅仅发布一个代码 sn-p 通常是不够的。
    【解决方案4】:

    LocationTextExtractionStrategy 将自动在输出文本中插入“\n”。但是,有时它会在不应该插入的地方插入 '\n'。 在这种情况下,您需要构建自定义 TextExtractionStrategy 或 RenderListener。基本上检测换行符的代码就是方法

    public virtual bool SameLine(ITextChunkLocation other) {
                return OrientationMagnitude == other.OrientationMagnitude &&
                       DistPerpendicular == other.DistPerpendicular;
            }
    

    在某些情况下,如果 DistPerpendicular 和 other.DistPerpendicular 之间只有很小的差异,则不应插入 '\n',因此您需要将其更改为 Math.Abs​​(DistPerpendicular - other.DistPerpendicular)

    或者您可以将这段代码放在自定义 TextExtractionStrategy/RenderListener 类的 RenderText 方法中

    【讨论】:

      【解决方案5】:

      使用 LocationTextExtractionStrategy 代替 SimpleTextExtractionStrategy。 LocationTextExtractionStrategy 提取的文本在行尾包含换行符。

      ITextExtractionStrategy Strategy = new FilteredTextRenderListener(new LocationTextExtractionStrategy(), renderFilter);
      string pdftext = PdfTextExtractor.GetTextFromPage(reader,pageno, Strategy);
      string[] words = pdftext.Split('\n');
      return words;
      

      【讨论】:

        【解决方案6】:

        试试

         String page = PdfTextExtractor.getTextFromPage(reader, 2);
         String s1[]=page.split("\n"); 
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2023-01-08
          • 2014-06-06
          • 1970-01-01
          • 2017-09-19
          • 1970-01-01
          • 1970-01-01
          • 2015-11-19
          • 1970-01-01
          相关资源
          最近更新 更多