Read text from PDF on .NET Core using Any open source / non-licensed packages

Viewed 12583

I need to read PDF and convert it in a .Txt. I tried iTextSharp as free library, it was working fine but not compatible with .NET Core.

Code snippet in iTextSharp

string prevPage = "";
for (int page = 5; page <= reader.NumberOfPages; page++)
{
  ITextExtractionStrategy its = new SimpleTextExtractionStrategy();
  var s = PdfTextExtractor.GetTextFromPage(reader, page, its);
  if (prevPage != s) sb.Append(s);
  prevPage = s;
}
reader.Close();

Also, I tried iTextSharp.LGPLv2.Core but it does not work as well as the other one, and the results are not accurate.

One of the downsides iTextSharp.LGPLv2.Core is that it does not support encoding and results in noise in the extracted text of the PDF

My stringbuilder looks like the image below:

enter image description here

1 Answers

Approach: PDFPig (Apache:2.0 License)

Install Nuget Package PdfPig

Tested on .Net Core 3.1

using (var stream = File.OpenRead(pdfPath1))
using (UglyToad.PdfPig.PdfDocument document = UglyToad.PdfPig.PdfDocument.Open(stream))
{
    var page = document.GetPage(2);
    return string.Join(" ", page.GetWords());
}

Approach: iTextSharp.LGPLv2.Core(GNU General Public License)

Install Nuget iTextSharp.LGPLv2.Core

It is an unofficial port of the last LGPL version of the iTextSharp (V4.1.6) to .NET Core.

Tested on .Net Core 3.1

var reader = new PdfReader(pdfPath1);
var streamBytes = reader.GetPageContent(1);
var tokenizer = new PrTokeniser(new RandomAccessFileOrArray(streamBytes));
var sb = new StringBuilder();
while (tokenizer.NextToken())
{
    if (tokenizer.TokenType == PrTokeniser.TK_STRING)
    {
         var currentText = tokenizer.StringValue;
         currentText = Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(currentText)));
         sb.Append(tokenizer.StringValue);
    }
}

Console.WriteLine("Extracted text "+sb);

Approach: GrapeCity.Documents.PDF(Licensed)

Install Nuget-Package *GrapeCity.Documents.Pdf
Is crossplatform library allows for creation, modification and analysis of PDF docs

Tested on .Net Core 3.1

    var doc = new GcPdfDocument();
    FileStream fs = new FileStream(pdfPath1, FileMode.Open, FileAccess.ReadWrite);
    doc.Load(fs);
    //To extract Page 1
    var tmap_page2 = doc.Pages[0].GetTextMap();
    tmap_page2.GetFragment(out TextMapFragment newFragment, out string Extractedtext);

    Console.WriteLine("Extracted Text: \n\n" +Extractedtext);
Related