Document save to stream automatically closes the stream

It seems that saving PDF document to MemoryStream, the stream will be closed automatically (after the document goes out of scope?) I would like to keep the stream open to read from it without having to copy to a new stream. It is possible?

I already ask a related question on StackOverflow


The reason why it’s closed is because the stream ends up being disposed with the PdfDocument.Dispose() call, that is the whole point of that method.

There are two ways how you can resolve your issue, first is to not call PdfDocument.Dispose() (in other words, remove the using statement):

var document = new PdfDocument();
var memoryStream = new MemoryStream();
// ...

The second solution is this:

using var document = new PdfDocument();
document.CloseStream = false;
var memoryStream = new MemoryStream();
// ...

Setting the PdfDocument.CloseStream option to false has the same effect as not calling PdfDocument.Dispose().

I hope this helps.


Thanks for the swift response, Mario.

Knowing that my document load some images from other streams. Would I be safe not using the document object?

Yes, even in that case it would be safe.

You see, the PdfDocument.Close() and PdfDocument.Dispose() only close the associated PDF file (or PDF stream).
Perhaps for a wider context, please read the following help page: