Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iTextSharp IndexOutOfRange

Tags:

c#

.net

itext

Keep getting IndexOutOfRangeException was unhandled exception.

var sb = new StringBuilder();
var bdn = String.Format("{0}\\bdn.pdf", Application.StartupPath);
var reader = new PdfReader("bdn.pdf");
var numberOfPages = reader.NumberOfPages;
for (var currentPageIndex = 1; currentPageIndex <= numberOfPages; currentPageIndex++)
{
        sb.Append(PdfTextExtractor.GetTextFromPage(reader, currentPageIndex));
}
like image 421
Nathan Russell Avatar asked Jul 10 '26 14:07

Nathan Russell


1 Answers

Make sure you're running an iTextSharp version greater than 5.1, which had a bug that exactly matches your problem:

  • iTextSharp v5 GetTextFromPage() throws IndexOutOfRangeException
  • Index was outside the bounds of the array while reading a .Pdf using iTextSharp

Just tested with 5.5.4.0 (latest version), using this code, which works:

    StringBuilder sb = new StringBuilder();
// substitute 'pdfPath' with path to YOUR PDF
    PdfReader reader = new PdfReader(pdfPath);
    int pageNumber = 1;
    while (pageNumber <= reader.NumberOfPages) {
      sb.Append(PdfTextExtractor.GetTextFromPage(reader, pageNumber));
      ++pageNumber;
    }
like image 75
kuujinbo Avatar answered Jul 12 '26 07:07

kuujinbo