Your problem lies within your for loop
:
for (var currentPageIndex = 1; currentPageIndex <= numberOfPages; currentPageIndex++)
{
PdfTextExtractor.GetTextFromPage(reader, currentPageIndex);
}
There are a couple of problems with the above code:
Problem #1
I don't know your reasons for starting at index 1
, rather than index 0
, since collections and arrays in C#
start at index 0
... perhaps you're trying to skip the first page. If you do start at index 1
, understand that you're starting the count on the second page. This brings me to the second problem...
Problem #2
currentPageIndex <= numberOfPages
As an example, if currentPageIndex
is 3
and numberOfPages
is 3
, this expression would evaluate to true
, allowing the code within the block to execute. However, numberOfPages
indicates the length/count of the array/collection. Thus, the last valid index for the length of 3
, would be index 2
.
You must change it to:
currentPageIndex < numberOfPages
... since currentPageIndex
must remain less than the total number pages. Otherwise, it will be out of bounds.
I would also recommend learning how to debug, so that you may either step through your code or check the values at the time the exception gets thrown.