Search code examples
c#asp.netasp.net-mvcpdfcrystal-reports

ASP MVC - Creating a PDF in controller and displaying as HTML object


I would like to create a PDF file in a controller (based on a Crystal Report), serve it back to the user in an HTML object. My current iteration of the following controller simply returns a File Stream, which just loads the PDF document. In order to display the PDF to the user in an iframe or HTML object, is it required to first save the PDF to the server and then return the path to my view? What is the best way to accomplish this task? Thanks!

[HttpPost]
public ActionResult Index(string test)
{
    ReportClass rptH = new ReportClass();

    rptH.FileName = Server.MapPath(@"~/Reports/Report.rpt");
    rptH.SetParameterValue("@ID", 33);
    rptH.Load();
    Stream stream = rptH.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);

    return File(stream, "application/pdf");   
} 

Solution

  • Did you try using FileStreamResult:

    Controller

        [HttpGet]
        public ActionResult DisplayPdfInIframe(string test)
        {
            ReportClass rptH = new ReportClass();
    
            rptH.FileName = Server.MapPath(@"~/Reports/Report.rpt");
            rptH.SetParameterValue("@ID", 33);
            rptH.Load();
            Stream stream = rptH.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
    
            return new FileStreamResult(stream, "application/pdf");
        } 
    

    View

     <iframe src="@Url.Action("DisplayPdfInIframe", "YourController")"></iframe>