Mikhail Umnov
Mikhail Umnov

Reputation: 13

iText 7 - Parsing exception in PdfReader constructor closes the input stream unexpectedly

I'm facing an issue after upgrading to latest version of iText for .NET (7.1.15 -> 7.1.16).

Please see example code below:

Stream pdfStream = GetPdfStream(...);

try
{
    IRandomAccessSource randomAccessSource = new RandomAccessSourceFactory().CreateSource(pdfStream);
    ReaderProperties readerProperties = new ReaderProperties
    {
        // ...
    };

    using (var pdfReader = new PdfReader(randomAccessSource, readerProperties))
    {
        pdfReader.SetCloseStream(false);

        // do things with pdfReader
    }
}
catch
{
    // ...
}

// reuse pdfStream somewhere else

In this situation if the file can not be parsed I'm getting the exception (expected):

iText.IO.IOException: PDF header not found.
   at iText.Kernel.Pdf.PdfReader.GetOffsetTokeniser(IRandomAccessSource byteSource)
   at iText.Kernel.Pdf.PdfReader..ctor(IRandomAccessSource byteSource, ReaderProperties properties)

But as an unexpected side effect it also closes the input Stream, which wasn't happening in the previous version (7.1.15). Because the exception happens in PdfReader constructor it also can not yet reach pdfReader.SetCloseStream.

Is there any way to prevent PdfReader from closing the externally provided input stream? Or any chance of a new constructor API that would take 'leaveOpen' parameter like .NET StreamReader does.

Upvotes: 1

Views: 983

Answers (1)

Alexey Subach
Alexey Subach

Reputation: 12302

The bug is fixed in 7.2.0-SNAPSHOT and 7.1.17-SNAPSHOT versions. You can fetch those versions from iText Artifactory using the following Maven configuration:

<repositories>
  <repository>
    <id>itext-snapshot</id>
    <name>iText Repository - snapshots</name>
    <url>https://repo.itextsupport.com/snapshot</url>
  </repository>
<repositories>

Beware that 7.2.0-SNAPSHOT version contains breaking changes compared to 7.1.16-SNAPSHOT since 7.2.x line is considered a major upgrade compared to 7.1.x line.

Upvotes: 1

Related Questions