2008-09-17 69 views
62

是否有一个开放源代码库可以帮助我在.Net/C#中读取/解析P​​DF文档?在.Net中读取PDF文档

+0

由布洛克Nusser提供的答案看起来像最先进的最新解决方案,应该被认为是正确的答案这个问题 – ceetheman 2018-01-11 15:38:47

回答

50

iTextSharp是最好的选择。用它为lucene.Net制作蜘蛛,以便抓取PDF。

using System; 
using System.IO; 
using iTextSharp.text.pdf; 
using System.Text.RegularExpressions; 

namespace Spider.Utils 
{ 
    /// <summary> 
    /// Parses a PDF file and extracts the text from it. 
    /// </summary> 
    public class PDFParser 
    { 
     /// BT = Beginning of a text object operator 
     /// ET = End of a text object operator 
     /// Td move to the start of next line 
     /// 5 Ts = superscript 
     /// -5 Ts = subscript 

     #region Fields 

     #region _numberOfCharsToKeep 
     /// <summary> 
     /// The number of characters to keep, when extracting text. 
     /// </summary> 
     private static int _numberOfCharsToKeep = 15; 
     #endregion 

     #endregion 

     #region ExtractText 
     /// <summary> 
     /// Extracts a text from a PDF file. 
     /// </summary> 
     /// <param name="inFileName">the full path to the pdf file.</param> 
     /// <param name="outFileName">the output file name.</param> 
     /// <returns>the extracted text</returns> 
     public bool ExtractText(string inFileName, string outFileName) 
     { 
      StreamWriter outFile = null; 
      try 
      { 
       // Create a reader for the given PDF file 
       PdfReader reader = new PdfReader(inFileName); 
       //outFile = File.CreateText(outFileName); 
       outFile = new StreamWriter(outFileName, false, System.Text.Encoding.UTF8); 

       Console.Write("Processing: "); 

       int totalLen = 68; 
       float charUnit = ((float)totalLen)/(float)reader.NumberOfPages; 
       int totalWritten = 0; 
       float curUnit = 0; 

       for (int page = 1; page <= reader.NumberOfPages; page++) 
       { 
        outFile.Write(ExtractTextFromPDFBytes(reader.GetPageContent(page)) + " "); 

        // Write the progress. 
        if (charUnit >= 1.0f) 
        { 
         for (int i = 0; i < (int)charUnit; i++) 
         { 
          Console.Write("#"); 
          totalWritten++; 
         } 
        } 
        else 
        { 
         curUnit += charUnit; 
         if (curUnit >= 1.0f) 
         { 
          for (int i = 0; i < (int)curUnit; i++) 
          { 
           Console.Write("#"); 
           totalWritten++; 
          } 
          curUnit = 0; 
         } 

        } 
       } 

       if (totalWritten < totalLen) 
       { 
        for (int i = 0; i < (totalLen - totalWritten); i++) 
        { 
         Console.Write("#"); 
        } 
       } 
       return true; 
      } 
      catch 
      { 
       return false; 
      } 
      finally 
      { 
       if (outFile != null) outFile.Close(); 
      } 
     } 
     #endregion 

     #region ExtractTextFromPDFBytes 
     /// <summary> 
     /// This method processes an uncompressed Adobe (text) object 
     /// and extracts text. 
     /// </summary> 
     /// <param name="input">uncompressed</param> 
     /// <returns></returns> 
     public string ExtractTextFromPDFBytes(byte[] input) 
     { 
      if (input == null || input.Length == 0) return ""; 

      try 
      { 
       string resultString = ""; 

       // Flag showing if we are we currently inside a text object 
       bool inTextObject = false; 

       // Flag showing if the next character is literal 
       // e.g. '\\' to get a '\' character or '\(' to get '(' 
       bool nextLiteral = false; 

       //() Bracket nesting level. Text appears inside() 
       int bracketDepth = 0; 

       // Keep previous chars to get extract numbers etc.: 
       char[] previousCharacters = new char[_numberOfCharsToKeep]; 
       for (int j = 0; j < _numberOfCharsToKeep; j++) previousCharacters[j] = ' '; 


       for (int i = 0; i < input.Length; i++) 
       { 
        char c = (char)input[i]; 
        if (input[i] == 213) 
         c = "'".ToCharArray()[0]; 

        if (inTextObject) 
        { 
         // Position the text 
         if (bracketDepth == 0) 
         { 
          if (CheckToken(new string[] { "TD", "Td" }, previousCharacters)) 
          { 
           resultString += "\n\r"; 
          } 
          else 
          { 
           if (CheckToken(new string[] { "'", "T*", "\"" }, previousCharacters)) 
           { 
            resultString += "\n"; 
           } 
           else 
           { 
            if (CheckToken(new string[] { "Tj" }, previousCharacters)) 
            { 
             resultString += " "; 
            } 
           } 
          } 
         } 

         // End of a text object, also go to a new line. 
         if (bracketDepth == 0 && 
          CheckToken(new string[] { "ET" }, previousCharacters)) 
         { 

          inTextObject = false; 
          resultString += " "; 
         } 
         else 
         { 
          // Start outputting text 
          if ((c == '(') && (bracketDepth == 0) && (!nextLiteral)) 
          { 
           bracketDepth = 1; 
          } 
          else 
          { 
           // Stop outputting text 
           if ((c == ')') && (bracketDepth == 1) && (!nextLiteral)) 
           { 
            bracketDepth = 0; 
           } 
           else 
           { 
            // Just a normal text character: 
            if (bracketDepth == 1) 
            { 
             // Only print out next character no matter what. 
             // Do not interpret. 
             if (c == '\\' && !nextLiteral) 
             { 
              resultString += c.ToString(); 
              nextLiteral = true; 
             } 
             else 
             { 
              if (((c >= ' ') && (c <= '~')) || 
               ((c >= 128) && (c < 255))) 
              { 
               resultString += c.ToString(); 
              } 

              nextLiteral = false; 
             } 
            } 
           } 
          } 
         } 
        } 

        // Store the recent characters for 
        // when we have to go back for a checking 
        for (int j = 0; j < _numberOfCharsToKeep - 1; j++) 
        { 
         previousCharacters[j] = previousCharacters[j + 1]; 
        } 
        previousCharacters[_numberOfCharsToKeep - 1] = c; 

        // Start of a text object 
        if (!inTextObject && CheckToken(new string[] { "BT" }, previousCharacters)) 
        { 
         inTextObject = true; 
        } 
       } 

       return CleanupContent(resultString); 
      } 
      catch 
      { 
       return ""; 
      } 
     } 

     private string CleanupContent(string text) 
     { 
      string[] patterns = { @"\\\(", @"\\\)", @"\\226", @"\\222", @"\\223", @"\\224", @"\\340", @"\\342", @"\\344", @"\\300", @"\\302", @"\\304", @"\\351", @"\\350", @"\\352", @"\\353", @"\\311", @"\\310", @"\\312", @"\\313", @"\\362", @"\\364", @"\\366", @"\\322", @"\\324", @"\\326", @"\\354", @"\\356", @"\\357", @"\\314", @"\\316", @"\\317", @"\\347", @"\\307", @"\\371", @"\\373", @"\\374", @"\\331", @"\\333", @"\\334", @"\\256", @"\\231", @"\\253", @"\\273", @"\\251", @"\\221"}; 
      string[] replace = { "(",  ")",  "-",  "'",  "\"",  "\"", "à",  "â",  "ä",  "À",  "Â",  "Ä",  "é",  "è",  "ê",  "ë",  "É",  "È",  "Ê",  "Ë",  "ò",  "ô",  "ö",  "Ò",  "Ô",  "Ö",  "ì",  "î",  "ï",  "Ì",  "Î",  "Ï",  "ç",  "Ç",  "ù",  "û",  "ü",  "Ù",  "Û",  "Ü",  "®",  "™",  "«",  "»",  "©",  "'" }; 

      for (int i = 0; i < patterns.Length; i++) 
      { 
       string regExPattern = patterns[i]; 
       Regex regex = new Regex(regExPattern, RegexOptions.IgnoreCase); 
       text = regex.Replace(text, replace[i]); 
      } 

      return text; 
     } 

     #endregion 

     #region CheckToken 
     /// <summary> 
     /// Check if a certain 2 character token just came along (e.g. BT) 
     /// </summary> 
     /// <param name="tokens">the searched token</param> 
     /// <param name="recent">the recent character array</param> 
     /// <returns></returns> 
     private bool CheckToken(string[] tokens, char[] recent) 
     { 
      foreach (string token in tokens) 
      { 
       if ((recent[_numberOfCharsToKeep - 3] == token[0]) && 
        (recent[_numberOfCharsToKeep - 2] == token[1]) && 
        ((recent[_numberOfCharsToKeep - 1] == ' ') || 
        (recent[_numberOfCharsToKeep - 1] == 0x0d) || 
        (recent[_numberOfCharsToKeep - 1] == 0x0a)) && 
        ((recent[_numberOfCharsToKeep - 4] == ' ') || 
        (recent[_numberOfCharsToKeep - 4] == 0x0d) || 
        (recent[_numberOfCharsToKeep - 4] == 0x0a)) 
        ) 
       { 
        return true; 
       } 
      } 
      return false; 
     } 
     #endregion 
    } 
} 
+1

hello ceetheman,我试着用你上面提供的代码... 但是遇到了一个问题。我的一些pdf文件被正确读取,但在某些pdf文件中,我在函数 “CheckToken”中收到错误“索引超出范围”。你能帮我解决这个问题吗? – Radhi 2010-02-22 12:38:58

+12

引用你的例子的来源是一个好的&礼貌的想法。 在这种情况下,可以在这里找到相同的源代码http://www.codeproject.com/KB/cs/PDFToText.aspx – Myster 2010-04-29 00:22:33

4

PDFClown可能有帮助,但我不会推荐它的一大或大量使用的应用程序。

+0

非常好的解决方案a – Evgeny 2011-02-11 10:18:52

3

iText的是我知道的最好的图书馆。最初用Java编写,还有一个.NET端口。

http://www.ujihara.jp/iTextdotNET/en/

+0

这不是一个官方的端口,并且该链接无论如何都被打破。 iText,iTextSharp的官方.NET端口可以在GitHub上找到:http://github.com/itext/itextsharp – 2015-12-09 15:39:55

4

我以前用ITextSharp来操作/分割和改造PDF文档 - 它非常简单,也是开源的。

5
public string ReadPdfFile(object Filename, DataTable ReadLibray) 
{ 
    PdfReader reader2 = new PdfReader((string)Filename); 
    string strText = string.Empty; 

    for (int page = 1; page <= reader2.NumberOfPages; page++) 
    { 
    ITextExtractionStrategy its = new iTextSharp.text.pdf.parser.SimpleTextExtractionStrategy(); 
    PdfReader reader = new PdfReader((string)Filename); 
    String s = PdfTextExtractor.GetTextFromPage(reader, page, its); 

    s = Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(s))); 
    strText = strText + s; 
    reader.Close(); 
    } 
    return strText; 
} 
76

由于这个问题是在2008年最后回答,iTextSharp大大改善了他们的API。如果您从http://sourceforge.net/projects/itextsharp/下载最新版本的api,则可以使用以下代码片段将PDF中的所有文本提取为字符串。

using iTextSharp.text.pdf; 
using iTextSharp.text.pdf.parser; 

namespace PdfParser 
{ 
    public static class PdfTextExtractor 
    { 
     public static string pdfText(string path) 
     { 
      PdfReader reader = new PdfReader(path); 
      string text = string.Empty; 
      for(int page = 1; page <= reader.NumberOfPages; page++) 
      { 
       text += PdfTextExtractor.GetTextFromPage(reader,page); 
      } 
      reader.Close(); 
      return text; 
     } 
    } 
} 
0

看看Docotic.Pdf library。它不要求你打开你的应用程序的源代码(例如iTextSharp具有病毒性的AGPL 3许可证)。

Docotic.Pdf可用于阅读PDF文件并提取带或不带格式的文本。请查看显示how to extract text from PDFs的示例。

声明:我为图书馆供应商Bit Miracle工作。