Q:

Error when extracting text

Unable to cast object of type 'iTextSharp.text.pdf.PdfLiteral' to type 'iTextSharp.text.pdf.PdfNumber'.
CODE:
StringBuilder text = new StringBuilder();

SimpleTextExtractionStrategy strategy = new SimpleTextExtractionStrategy();

for (int p = 1; p <= reader.NumberOfPages; p++)
{

    text.AppendLine(PdfTextExtractor.GetTextFromPage(reader, p, strategy));
}
reader.Close();
return text.ToString();

Only get this error with a very few pdfs. Any ideas?
STACK TRACE:
   at iTextSharp.text.pdf.parser.PdfContentStreamProcessor.ShowTextArray.Invoke(PdfContentStreamProcessor processor, PdfLiteral oper, List`1 operands)
   at iTextSharp.text.pdf.parser.PdfContentStreamProcessor.InvokeOperator(PdfLiteral oper, List`1 operands)
   at iTextSharp.text.pdf.parser.PdfContentStreamProcessor.ProcessContent(Byte[] contentBytes, PdfDictionary resources)
   at iTextSharp.text.pdf.parser.PdfReaderContentParser.ProcessContent[E](Int32 pageNumber, E renderListener)
   at iTextSharp.text.pdf.parser.PdfTextExtractor.GetTextFromPage(PdfReader reader, Int32 pageNumber, ITextExtractionStrategy strategy)
   at DCS.Common.PDF.Functions.GetTextPdf(PdfReader reader) in C:\Users\rmaldonado\Documents\Visual Studio 2008\Projects\DCS\Contract\Common\PDF\Functions.cs:line 35
   at DCS.Common.PDF.Functions.ParsePDF(Byte[] bytes) in C:\Users\rmaldonado\Documents\Visual Studio 2008\Projects\DCS\Contract\Common\PDF\Functions.cs:line 23
   at DCS.CAPPS.BLL.Common.Attachment.ReParseText() in C:\Users\rmaldonado\Documents\Visual Studio 2008\Projects\DCS\Contract\ContractBLL\Common\Common.cs:line 1120

A:

The page content of your document Mod 2.pdf is utterly broken. It actually is broken so badly Adobe Preflight (from Acrobat 9.5.4) just like iText runs into an error while trying to analyze it.
A manual inspection indicates that the most obvious errors relate to operations injected into an array of operands of TJ operations, e.g.
[(OMB) 0.0 Tc -278.0 (Approval) 0.0 Tc -278.0 (2700-0042) ] TJ

[(AMENDMENT) 0.0 Tc -278.0 (OF) 0.0 Tc -278.0 (SOLICITATION/MODIFICATION)
 0.0 Tc -278.0 (OF) 0.0 Tc -278.0 (CONTRACT) ] TJ

This pattern continues, i.e. every non-trivial [ ... ] TJ operation contains injected 0.0 Tc operations.
This is wrong, cf. section 7.8.2 of the PDF specification ISO 32000-1:2008: 

In PDF, all of the operands needed by an operator shall immediately precede that operator. Operators do not return results, and operands shall not be left over when an operator finishes execution.

This makes PdfContentStreamProcessor.ShowTextArray.Invoke (responsible for processing TJ operations) run into the error. As the operand array of TJ may contain only strings and numbers, everything which is not a PdfString, is cast to PdfNumber but the Tc operators are instances of PdfLiteral.

