If you are using 'iTextSharp' library to read/write PDF files in your application and faced an InvalidCastException with the message "Unable to cast object of type 'iTextSharp.text.pdf.PdfLiteral' to type 'iTextSharp.text.pdf.PdfString'", this post will help you to know the root cause of the issue. Continue reading to learn more about it.
'iTextSharp' is a very popular 3rd party library to read/write PDF documents using C#. It also has supported library for Java. If you are using the library in your application, you already know the power of it.
While processing/reading few PDF documents, the library may through the following InvalidCastException, that states the message: "Unable to cast object of type 'iTextSharp.text.pdf.PdfLiteral' to type 'iTextSharp.text.pdf.PdfString'" with the following Stack Trace:
The library parses the syntax of the PDF file to find specific PDF objects. When it detects some unidentifiable objects that doesnot fit into any of the defined PDF objects in the specification, it creates a PdfLiteral object from it.
When those unidentifiable PdfLiteral object is expected to read as PdfString, the iTextSharp library throws the above InvalidCastException. If you check the Stack Trace, you will notice that the internal code line iTextSharp.text.pdf.parser.PdfContentStreamProcessor.GetFont(PRIndirectReference ind) actually triggered the Exception.
As stated in StackOverflow, the PDF document, which threw the exception, contains a font 'Calibri' (which is a subset composite font) with the following ToUnicode map:
If you observe the above sample unicode map, you could find a 'beginbfchar' without a 'endbfchar'. Instead, it ended with 'endcmap' which caused the above exception to trigger (check the highlighted code above).
If you faced this exception in your application, nothing wrong in your code. You just need to handle it properly so that, you can skip reading those PDF documents in the question for the InvalidCastException from iTextSharp library. Hope the post was helpful. Don't forget to ask your question, if any.