Saving a Pdf to a MemoryStream

In C#, I’m trying to save a Pdf to a MemoryStream and then convert the stream to an array of bytes (to save to a database). However, at the point where I call the .Save method on the Pdf I get a ‘Cannot access a closed Stream’ exception, even on a stream that I’ve just created.

Here’s my code:

public byte[] generatePdf()
{
    Pdf masterDocument = new Pdf();

    // Do document generation  here...

    byte[] documentBytes;

    using (MemoryStream documentStream = new MemoryStream())
    {
        // This line throws the 'Cannot access a closed Stream' exception
        masterDocument.Save(documentStream);

        documentBytes = documentStream.ToArray();
    }
    return documentBytes;
}

Is there something I’m doing incorrectly?

@bis4pp

Thank you for contacting support.

I have worked with the code shared by you and I am unable to reproduce the issue with latest version of Aspose.Pdf, i.e Aspose.Pdf for .NET 17.12. Please upgrade to latest version and use below code in your environment. It has been modified to work with latest version of the API.

public byte[] generatePdf()
    {
        Document masterDocument = new Document( dataDir + "test.pdf");

        // Do document generation  here...

        byte[] documentBytes;

        using (MemoryStream documentStream = new MemoryStream())
        {
            masterDocument.Save( dataDir + documentStream + ".pdf");

            documentBytes = documentStream.ToArray();
        }
        return documentBytes;
    }

I hope this will be helpful. Please let us know if you need any further assistance.