pvginkel / PdfiumViewer

PDF viewer based on Google's PDFium.
Apache License 2.0
966 stars 418 forks source link

Leaving open files when opening bad PDF or not a PDF file #150

Open neojg opened 6 years ago

neojg commented 6 years ago

In case one try to open a file that is either not a PDF or is somehow corrupted a call to Load leavs the file open.

The problem is in the PdfFile.cs file. The possible solution may look like:

public PdfFile(Stream stream, string password)
    {
        if (stream == null)
            throw new ArgumentNullException(nameof(stream));

        PdfLibrary.EnsureLoaded();

        _stream = stream;
        _id = PdfStreamManager.Register(stream);

        IntPtr document = IntPtr.Zero;

        try
        {
            document = NativeMethods.FPDF_LoadCustomDocument(stream, password, _id);
            if (document == IntPtr.Zero)
                throw new PdfException((PdfError)NativeMethods.FPDF_GetLastError());

            LoadDocument(document);
        }
        catch (Exception ex)
        {
            stream.Dispose();
            PdfStreamManager.Unregister(_id);
            throw ex;
        }
    }