C#C
C#2y ago
Turwaith

ObjectDisposedException: Cannot access a closed Stream. I don't understand why it doesn't work.

I am receiving a pdf document via a http get request and I need to rescale the actual document size. For this, I have written the following method, using the itext7 nuget package:
private static Stream CompressPdf(Stream inputStream, float scaleFactor = 0.5f)
{
    var outputStream = new MemoryStream();
    inputStream.Position = 0;
    var pdfReader = new PdfReader(inputStream);
    var pdfWriter = new PdfWriter(outputStream);
    var pdfDocument = new PdfDocument(pdfReader, pdfWriter);
    int numberOfPages = pdfDocument.GetNumberOfPages();
    for (int i = 1; i <= numberOfPages; i++)
    {
        PdfPage page = pdfDocument.GetPage(i);
        Rectangle originalPageSize = page.GetPageSize();
        float newWidth = originalPageSize.GetWidth() * scaleFactor;
        float newHeight = originalPageSize.GetHeight() * scaleFactor;
        var newPageSize = new PageSize(newWidth, newHeight);
        page.SetMediaBox(newPageSize);
        page.SetCropBox(newPageSize);
        var canvas = new PdfCanvas(page);
        canvas.ConcatMatrix(scaleFactor, 0, 0, scaleFactor, 0, 0);
    }
    pdfDocument.Close();
    outputStream.Position = 0;
    return outputStream;
}

With this code, I get a ObjectDisposedException with the message Cannot access a closed Stream. The exception is thrown at the line
outputStream.Position = 0;


I don't understand why I get this exception. In an earlier version, I was using using for both the PdfReader and the PdfWriter. But even after removing that, I still get this error.
Was this page helpful?