pvginkel / PdfiumViewer

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

Memory usage #60

Closed jasonhendrix closed 8 years ago

jasonhendrix commented 8 years ago

I noticed that if I opened a sample PDF, closed it, opened a different sample, and repeated the process that the memory usage continually increased.

So I used the PdfiumViewer.Demo project and the only change I made was to make the project use .NET Framework 4.6.1 rather than the default so that I could use the built in memory diagnostic tool in Visual Studio. The same problem happened there as well.

Is there something I should do to properly dispose items once finished viewing a given file?

pvginkel commented 8 years ago

The problem most likely is that the PdfDocument isn't disposed. The viewer doesn't do this for you and you're supposed to do this yourself. Easiest way to do this is to add the following line in the constructor of your form:

Disposed += (s, e) => pdfViewer1.Document.Dispose();

Or to make it a little bit nicer:

Disposed += (s, e) =>
{
    var document = pdfViewer1.Document;
    if (document != null)
        document.Dispose();
};

Of course, whenever you assign to pdfViewer1.Document, you also have to make sure you dispose the existing one:

private void OpenDocument(PdfDocument document)
{
    if (pdfViewer1.Document != null)
        pdfViewer1.Document.Dispose();

    pdfViewer1.Document = document;
}

The reason the component is not doing this for you because the component does not take ownership of the document. Instead, you keep ownership. This is the same as e.g. PictureBox works. That won't dispose of Image instances for you either.

rearintok commented 8 years ago

still not disposing when i load from stream

Dim pdf_stream As Stream = stream Dim pdfdoc = PdfDocument.Load(pdf_stream) _pdf = pdfdoc

Dim f As New PdfViewer f.Parent = pnlPreview f.Dock = DockStyle.Fill If f.Document IsNot Nothing Then f.Document.Dispose() End If f.Document = PdfDocument.Load(pdf_stream) f.Visible = True

even i use the dispose you provided still not working..this only works if i clear the parent panel..but i don't want to clear the panel, because the viewer is already loaded, please help