Click here to Skip to main content
15,119,335 members
Articles / Web Development / HTML
Article
Posted 1 Dec 2005

Stats

1.7M views
31.1K downloads
483 bookmarked

Converting PDF to Text in C#

Rate me:
Please Sign up or sign in to vote.
4.80/5 (143 votes)
19 Apr 2015CPOL3 min read
Parsing PDF files in .NET using PDFBox and IKVM.NET (managed code).

Update

April 20, 2015: The article and the Visual Studio project are updated and work with the latest PDFBox version (1.8.9). It's also possible to download the project with all dependencies (resolving the dependencies proved to be a bit tricky).

February 27, 2014: This article originally described parsing PDF files using PDFBox. It has been extended to include samples for IFilter and iTextSharp.

How to Parse PDF Files

There are several main methods for extracting text from PDF files in .NET:

  • Microsoft IFilter interface and Adobe IFilter implementation.
  • iTextSharp
  • PDFBox

None of these PDF parsing solutions is perfect. We will discuss all these methods below.

1. Parsing PDF using Adobe PDF IFilter

In order to parse PDF files using IFilter interface you need the following:

Sample code:

using IFilter;

// ...

public static string ExtractTextFromPdf(string path) {
  return DefaultParser.Extract(path); 
} 

Download a sample project:

If you are using the PDF IFilter that comes with Adobe Acrobat Reader you will need to rename the process to "filtdump.exe" otherwise the IFilter interface will return E_NOTIMPL error code. See more at Parsing PDF Files using IFilter [squarepdf.net].

Disadvantages:

  1. Using unreliable COM interop that handles IFilter interface (and the combination of IFilter COM and Adobe PDF IFilter is especially troublesome).
  2. A separate installation of Adobe IFilter on the target system. This can be painful if you need to distribute your indexing solution to someone else.
  3. You have to use "filtdump.exe" file name for your application with the latest PDF IFilter implementation that comes with Acrobat Reader.

2. Parsing PDF using iTextSharp

iTextSharp is a .NET port of iText, a PDF manipulation library for Java. It is primarily focused on creating and not reading PDFs but it supports extracting text from PDF as well.

Sample code:

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

// ...
 
public static string ExtractTextFromPdf(string path)
{
  using (PdfReader reader = new PdfReader(path))
  {
    StringBuilder text = new StringBuilder();

    for (int i = 1; i <= reader.NumberOfPages; i++)
    {
        text.Append(PdfTextExtractor.GetTextFromPage(reader, i));
    }

    return text.ToString();
  }
} 

Credit: Member 10364982

Download a sample project:

You may consider using LocationTextExtractionStrategy to get better precision.

public static string ExtractTextFromPdf(string path)
{
  ITextExtractionStrategy its = new iTextSharp.text.pdf.parser.LocationTextExtractionStrategy();
  
  using (PdfReader reader = new PdfReader(path))
  {
      StringBuilder text = new StringBuilder();

      for (int i = 1; i <= reader.NumberOfPages; i++)
      {
          string thePage = PdfTextExtractor.GetTextFromPage(reader, i, its);
          string[] theLines = thePage.Split('\n');
          foreach (var theLine in theLines)
          {
              text.AppendLine(theLine);
          }
      }
      return text.ToString();
  }
}  

 

Credit: Member 10140900

Disadvantages of iTextSharp:

  1. Licensing if you are not happy with AGPL license

3. Parsing PDF using PDFBox

PDFBox is another Java PDF library. It is also ready to be used with the original Java Lucene (see LucenePDFDocument).

Fortunately, there is a .NET version of PDFBox that is created using IKVM.NET (just download the PDFBox package).

Using PDFBox in .NET requires adding references to:

  • IKVM.OpenJDK.Core.dll
  • IKVM.OpenJDK.SwingAWT.dll
  • pdfbox-1.8.9.dll

and copying the following files the bin directory:

  • commons-logging.dll
  • fontbox-1.8.9.dll
  • IKVM.OpenJDK.Text.dll
  • IKVM.OpenJDK.Util.dll
  • IKVM.Runtime.dll

Using the PDFBox to parse PDFs is fairly easy:

C#
using org.apache.pdfbox.pdmodel;
using org.apache.pdfbox.util;

// ...

private static string ExtractTextFromPdf(string path)
{
  PDDocument doc = null;
  try {
    doc = PDDocument.load(path)
    PDFTextStripper stripper = new PDFTextStripper();
    return stripper.getText(doc);
  }
  finally {
    if (doc != null) {
      doc.close();
    }
  }
}  

Download a sample project:

The size of the required assemblies adds up to almost 18 MB:

  • IKVM.OpenJDK.Core.dll (4 MB)
  • IKVM.OpenJDK.SwingAWT.dll (6 MB)
  • pdfbox-1.8.9.dll (4 MB)
  • commons-logging.dll (82 kB)
  • fontbox-1.8.9.dll (180 kB)
  • IKVM.OpenJDK.Text.dll (800 kB)
  • IKVM.OpenJDK.Util.dll (2 MB)
  • IKVM.Runtime.dll (1 MB)

The speed is not so bad: Parsing the U.S. Copyright Act PDF (5.1 MB) took about 13 seconds.

Thanks to bobrien100 for improvements suggestions.

Disadvantages:

  1. IKVM.NET Dependencies (18 MB)
  2. Speed (especially the IKVM.NET warm-up time)

Related information

History

  • April 20, 2015 - Updated to work with the latest PDFBox release (1.8.9)
  • November 27, 2014 - Updated to work with the latest PDFBox release (1.8.7)
  • March 10, 2014 - IFilter file name limitations added, iTextSharp sample extended
  • February 27, 2014 - Samples for IFilter and iTextSharp added.
  • February 24, 2014 - Updated to work with the latest PDFBox release (1.8.4)
  • June 20, 2012 - Updated to work with the latest PDFBox release (1.7.0)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Dan Letecky
Czech Republic Czech Republic

Comments and Discussions

 
GeneralMy vote of 1 Pin
abmv22-Jul-09 1:14
professionalabmv22-Jul-09 1:14 
Questionhow i can convert pdf to HTML in C# ?? Pin
re7et_3esh2-Jul-09 2:48
Memberre7et_3esh2-Jul-09 2:48 
GeneralDocument is not getting loaded [modified] Pin
Spectacular#19-Jun-09 0:44
MemberSpectacular#19-Jun-09 0:44 
GeneralRead PDF file in C# with Images Pin
Saurabh_ClearDevelop26-May-09 22:56
MemberSaurabh_ClearDevelop26-May-09 22:56 
GeneralRe: Read PDF file in C# with Images Pin
eslsys19-Feb-10 8:03
professionaleslsys19-Feb-10 8:03 
QuestionExtracting tables data from PDF file ? Pin
Hanan Harush21-Mar-09 10:51
MemberHanan Harush21-Mar-09 10:51 
AnswerRe: Extracting tables data from PDF file ? Pin
Ivan Clay18-Nov-09 3:41
MemberIvan Clay18-Nov-09 3:41 
GeneralRe: Extracting tables data from PDF file ? Pin
VC Sekhar Parepalli9-Jul-10 7:19
MemberVC Sekhar Parepalli9-Jul-10 7:19 
Appreciate if any one can share some light here. Am also having a similar need to read field-values from a fillable-pdf.


Thanks in advance,

VC Sekhar Parepalli
GeneralThe type or namespace name 'GNU' does not exist in the namespace 'IKVM' Pin
m0965102-Feb-09 17:30
Memberm0965102-Feb-09 17:30 
GeneralRe: The type or namespace name 'GNU' does not exist in the namespace 'IKVM' Pin
Sundararajan10-Nov-09 8:25
MemberSundararajan10-Nov-09 8:25 
GeneralIs there a way to use this for URL Pin
MeCode12330-Jan-09 10:57
MemberMeCode12330-Jan-09 10:57 
GeneralWrappedIOException C# not working; but vb.net is working Pin
saif_200618-Jan-09 19:54
Membersaif_200618-Jan-09 19:54 
GeneralRe: WrappedIOException C# not working; but vb.net is working Pin
saif_200619-Jan-09 0:51
Membersaif_200619-Jan-09 0:51 
GeneralRe: its a request Pin
tkmsabarish8-Jan-10 21:29
Membertkmsabarish8-Jan-10 21:29 
Generalsolution for the type initializer for "java.io.file" threw an exception Pin
Daniel_Wilson12-Jan-09 1:01
MemberDaniel_Wilson12-Jan-09 1:01 
GeneralRe: solution for the type initializer for "java.io.file" threw an exception Pin
Flashr19-Feb-09 3:52
MemberFlashr19-Feb-09 3:52 
GeneralMy vote of 1 Pin
clarkapp3-Jan-09 18:50
Memberclarkapp3-Jan-09 18:50 
QuestionCan anybody tell me this? Pin
e40s27-Dec-08 15:30
Membere40s27-Dec-08 15:30 
GeneralI can't find a PDFBox-0.7.x.dll with a strong name. [modified] Pin
e40s26-Dec-08 12:39
Membere40s26-Dec-08 12:39 
GeneralRe: I can't find a PDFBox-0.7.x.dll with a strong name. Pin
Daniel_Wilson12-Jan-09 1:11
MemberDaniel_Wilson12-Jan-09 1:11 
QuestionNot working when convertring gujarati langugage Pin
Amitsp25-Dec-08 0:37
MemberAmitsp25-Dec-08 0:37 
GeneralCannot convert in correct format from Pdf file to MS -Word i.e doc file Pin
umeshrajpoot23-Dec-08 19:48
Memberumeshrajpoot23-Dec-08 19:48 
GeneralReading Table data from pdf documents Pin
dinesh choudhary9-Dec-08 23:43
Memberdinesh choudhary9-Dec-08 23:43 
Generalpdf with password Pin
mostafa alimohammadi7-Dec-08 5:09
Membermostafa alimohammadi7-Dec-08 5:09 
GeneralRe: pdf with password Pin
mostafa alimohammadi7-Dec-08 5:11
Membermostafa alimohammadi7-Dec-08 5:11 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.