Click here to Skip to main content
15,943,294 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have an MVC.NET application that returns a PDF stream. I am trying to embed that stream into a view. I have this action in a controller

    public ActionResult GetPDFStream(int reportId)
        byte[] pdfByteStream = GetReportBytes(reportId);
        Response.AddHeader("Content-Disposition","inline; filename=sample.pdf");
        Response.AddHeader("Content-Length", pdfByteStream.Length.ToString());
        return new FileContentResult(pdfByteStream, "application/pdf");

In my view I am trying both, the object tag and/or the iframe tag

<object data="'<%= Url.Action("GetPDFStream", "ResultActions", new {reportId = Model.reportId }) %>" #zoom=150′ width = "100%" height="525" id="iFramePdf" frameBorder="1" type="application/pdf"/>
<iframe src="'<%= Url.Action("GetPDFStream", "ResultActions", new {reportId = Model.reportId }) %>"/>

However, no matter what I do, the embedded PDF doesn't show. Instead, the error message is popping up saying

HTTP Error 404.0 - Not Found
The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.
When I get into a source, however, I am able to retrieve the link and confirm that the link works. Once I paste the link into a browser, it does display the PDF, but no PDF is displayed initially

Can someone please help

Thank you in advance

What I have tried:

No matter how much I tried with the scenario above, the PDF would not deisplay
Updated 25-Jul-23 16:18pm
Richard Deeming 10-Feb-22 8:15am    
You don't need to mess about clearing the response or setting the headers - the FileContentResult will do that for you:
public ActionResult GetPDFStream(int reportId)
    byte[] pdfByteStream = GetReportBytes(reportId);
    return new FileContentResult(pdfByteStream, "application/pdf");
Richard Deeming 10-Feb-22 8:16am    
Beyond that, a 404 error suggests the Url.Action is generating the wrong URL. View the source of the rendered page in your browser to see what URL is being generated, and then try requesting that URL directly.
Member 13304618 10-Feb-22 9:11am    
Thank you very much for commenting. In fact I did get the URL from the source, pasted that URL into a browser and WAS able to get the PDF displayed. Thank you once again
Richard Deeming 10-Feb-22 8:17am    
Also note that some browsers can't display a PDF in an <iframe>; for those browsers, you'd need to use something like pdf.js[^] to load and display the file.
Maciej Los 18-Feb-22 15:26pm    
All your suggestions are very valuable. I'd suggest to move them into answer ;)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900