VahidN / iTextSharp.LGPLv2.Core

iTextSharp.LGPLv2.Core is an unofficial port of the last LGPL version of the iTextSharp (V4.1.6) to .NET Core
Other
615 stars 154 forks source link

Specified cast is not valid while reading a TIFF file #127

Closed vsolominov closed 1 year ago

vsolominov commented 1 year ago

Summary of the issue

While reading a TIFF file, an error about the incorrect type occurs.

Environment

iTextSharp.LGPLv2.Core version: 3.4.7
.NET Core SDK version: 6.0
IDE: Visual Studio 2022

Example code/Steps to reproduce:

I'm trying to read a TIFF file like this:

var randomAccessor = new RandomAccessFileOrArray(input);
var pageCount = TiffImage.GetNumberOfPages(randomAccessor);
for (int pageIndex = 1; i <= pageCount; pageIndex++)
{
    var image = TiffImage.GetTiffImage(randomAccessor, pageIndex);
}

Problem when calling the GetField(tag) method on a tag that is not in the dictionary:

var fillOrderField = dir.GetField(TiffConstants.TIFFTAG_FILLORDER);
if (fillOrderField != null)
{
    fillOrder = fillOrderField.GetAsInt(0);
}

If we turn to the implementation, then if there is no tag in the _fieldIndex dictionary, the value 0 will be returned. Then _fields[0] is called, resulting in an incorrect value, without GetField(tag) returning null.

Output:

Exception message: Specified cast is not valid.
Full Stack trace:
  at iTextSharp.text.pdf.codec.TiffField.GetAsInt(Int32 index) in G:\iTextSharp.LGPLv2.Core\src\iTextSharp.LGPLv2.Core\iTextSharp\text\pdf\codec\TIFFField.cs:line 310
  at iTextSharp.text.pdf.codec.TiffImage.GetTiffImageColor(TiffDirectory dir, RandomAccessFileOrArray s) in G:\iTextSharp.LGPLv2.Core\src\iTextSharp.LGPLv2.Core\iTextSharp\text\pdf\codec\TiffImage.cs:line 443
  at iTextSharp.text.pdf.codec.TiffImage.GetTiffImage(RandomAccessFileOrArray s, Int32 page, Boolean direct) in G:\iTextSharp.LGPLv2.Core\src\iTextSharp.LGPLv2.Core\iTextSharp\text\pdf\codec\TiffImage.cs:line 110
  at iTextSharp.text.pdf.codec.TiffImage.GetTiffImage(RandomAccessFileOrArray s, Int32 page) in G:\\iTextSharp.LGPLv2.Core\src\iTextSharp.LGPLv2.Core\iTextSharp\text\pdf\codec\TiffImage.cs:line 77
  at Pdf.Program.Execute(String input, String output) in G:\Pdf\Program.cs:line 129