We're sorry Aspose doesn't work properply without JavaScript enabled.

Free Support Forum - aspose.com

Does disposing Aspose.Pdf.Document disposes underneath stream?

if i have code like

using(Aspose.Pdf.Document doc = new Aspose.Pdf.Document(“c:\temp\test.pdf”))
{
//do something here
}

does disposing Aspose.Pdf.Document actually disposes underneath file stream?

@Laksh

Thank you for contacting support.

Please note that Document.Dispose method implements IDisposable.Dispose method and closes all resources used by Document constructor.

We hope this will be helpful. Please feel free to contact us if you need any further assistance.

Hello,

i do not fully understand the text:

should it mean that only resources handed over to the constructor are released?

Or, as in the example:

        Page pdfPage = newPages.Add();
        // At the end, it is a image-stream in the pdf-page paragraph: (will be disposed from pdf-document dispose)
        // https://forum.aspose.com/t/does-disposing-aspose-pdf-document-disposes-underneath-stream/180276
        Stream preparedStream = new MemoryStream();

        try
        {
            // Use Bitmap to obtain image size: https://docs.aspose.com/display/pdfnet/How+to+++Set+page+orientation+according+to+image+dimensions)
            using (Bitmap tmpImage = new Bitmap(attachmentStream))
            {
                pdfPage.PageInfo.Margin = new MarginInfo(0, 0, 0, 0);
                //newPage.CropBox = new Aspose.Pdf.Rectangle( 0, 0, tmpImage.Width, tmpImage.Height );
                // Set page to Landscape if image is landscape => PageHeight and PageWidth will be switched
                if (tmpImage.Width > tmpImage.Height) pdfPage.PageInfo.IsLandscape = true;

                tmpImage.Save(preparedStream, System.Drawing.Imaging.ImageFormat.Jpeg);
            }
        }
        catch (Exception ex)
        { return base.SetError($"Error converting image '{fileName}' to Bitmap (see Exception for details).", ex); }

        Aspose.Pdf.Image currImage = new Aspose.Pdf.Image() { ImageStream = preparedStream };
        pdfPage.Paragraphs.Add(currImage);

will the image resource be released again?

Thanks in advance,
Thomas Eszterwitsch

@ThomasEsz

Thank you for contacting support.

Please note that when a file is loaded into Document constructor, Document Object Model (DOM) is loaded into memory and necessary resources are allocated. However, Dispose method frees any resource which was allocated previously to perform specific operation. However, the resources dedicated for MemoryStream and Image class will be released automatically when the application stops execution.

With when the application stops execution do you mean the application that uses the aspose library?

But that also means that these resources have to release themselves as I have indicated in the example?
Even if there is nowhere else except in the DOM a reference to the stream exists?

Thanks in advance,
Thomas Eszterwitsch

@ThomasEsz

Please note that we are referring to the application where instances of MemoryStream are initiated. Allocated resources will be released when application stops, unless the MemoryStream is disposed explicitly because Aspose.PDF API disposes the resources it has internally utilized to perform specific operations. Since the MemoryStream is not the instance created by the API but explicitly by the code, so it needs to be disposed separately.

In case you are facing any problem with memory leak or object disposal then please share the details so that we may investigate it accordingly to help you out.

Hello,

ok here the strongly reduced version of our code:

using Aspose.Pdf;
using System;
using System.Collections.Generic;
using System.IO;
using Playground.Enums;
using Playground.Objects.PdfConverter;
 
namespace Playground
{
 public abstract class Example
 {
     // Own converter, not aspose!
     private PdfConverter _PdfConverter = new PdfConverter();



    public string FileName { get; set; }

    public string NormalizedFileName { get; set; }

    public string FileExtension { get; set; }

    public string LastError { get; protected set; }

    public Exception LastException { get; protected set; }




    protected abstract bool GetStream(Stream stream);



    public bool GetPdfStream(Stream stream, AttachmentConversionEnum convertOption, int imageQuality, int dpi)
    {
        bool isValid = true;
        using (Stream attachmentStream = new MemoryStream())
        {
            List<Stream> openStreams = new List<Stream>();
            // Get current source stream:
            if (!this.GetStream(attachmentStream)) return false;

            Document convertedPdfDocument = null;
            using (Document pdfDocument = new Document())
            {
                // pdfDocument.Pages.Add(): create and add new page into document and returns the reference 
                if (!this._PdfConverter.GetPdfPages(this.NormalizedFileName, this.FileExtension, attachmentStream, pdfDocument.Pages, openStreams))
                { this.DisposeStreams(openStreams); return this.SetError(this._PdfConverter.LastError, this._PdfConverter.LastException); }

                if ((convertedPdfDocument = this._PdfConverter.ProcessingConvertOptionsForPdf(pdfDocument, convertOption, imageQuality, dpi)) == null)
                { this.DisposeStreams(openStreams); return this.SetError(this._PdfConverter.LastError, this._PdfConverter.LastException); }
            }

            try { convertedPdfDocument.Save(stream, new PdfConverterSaveOptions(true, SaveFormat.Pdf)); }
            catch (Exception ex)
            { isValid = this.SetError($"Creation of PDF document from attachment '{this.FileName}' failed (see Exception for details).", ex); }
            finally
            {
                this.DisposeStreams(openStreams);
                convertedPdfDocument.Dispose();
            }
        }

        return isValid;
    }



    protected void DisposeStreams(IEnumerable<Stream> streams)
    {
        if (streams == null) return;
        foreach (Stream st in streams) st?.Dispose();
    }



    private bool SetError(string errorMessage, Exception error = null)
    {
        this.LastError = errorMessage ?? "Unknown error!";
        this.LastException = error;
        return false;
    }

}

}

at _PdfConverter.GetPdfPages, the upper code with the image is used.

So, what is done here:
In the part with the image, the attachment stream is created as a picture object (which it is) and this object is passed as stream to the Aspose.Image object.
This transferred object is not released by us, as the assumption is that it is done when Dispose of Pdf.Document.

Is this correct?

( using (Document pdfDocument = new Document()); convertedPdfDocument.Dispose() is a copy of pdfDocument so that last changes are taken over, with Save())

@ThomasEsz

Thank you for elaborating it further.

We have logged a ticket with ID PDFNET-46106 in our issue management system for detailed investigations. We will let you know as soon as some significant updates will be available in this regard.