Search code examples
c#.netasp.net-mvcpdffilestream

Show PDF on webpage using Stream C#


I'm trying to embed PDF viewer to show PDF document on a webpage. When I run this code, it normally shows me PDF just like I want, but when I refresh, everything crashes (I get a message "Failed to load PDF Document"). The error that I actually get is "ObjectDisposedException: Cannot access a closed Stream.", so it might be something about the stream reading, I have no idea.

I don't know the document's path, so I simply retrieve Stream of a document through API (this works just fine), therefore Stream is the only thing I have available.

This is what I have done so far. What do you suggest to add/change?

Files1Controller.cs:

    public class Files1Controller : Controller
    {
        private IWebHostEnvironment hostingEnvironment;

        // Data is in here (I retrieve data from API in another class)
        private readonly DocumentData documentData;

        public Files1Controller(IWebHostEnvironment hostingEnvironment, DocumentData documentData)
        {
            this.hostingEnvironment = hostingEnvironment;

            this.documentData = documentData;
        }

        [HttpGet]
        public IActionResult Index()
        {
            return View(documentData);
        }

        public IActionResult PdfViewerNewTab()
        {
            return File(documentData.PdfFileStream, "application/pdf");
        }
    }
}

Index.cshtml:

@model DocumentData
@{
    Layout = null;
}

<embed id="embPDF" src="../Files1/[email protected]" style="width: 100%; height: 100%;" />

DocumentData:

public class DocumentData
{
        public string Filename { get; set; } = "long_line_file_ORIGINAl.pdf";

        public Stream PdfFileStream { get; set; }
}

Solution

  • Fetching file Stream through API directly in method PdfViewerNewTab() solved the issue.