0

I do AJAX call to generate PDF from crystal report.

Problem is , how to open PDF directly.

Below is my stuff. It looks, pdf is created but, it just return to view and not able to open PDF.

Please guide me.

Code:

      public ActionResult CreatePDF(string paramValue)
         {
          DataTable dt = new DataTable();
          DataColumn dc = new DataColumn("FieldName");
          dt.Columns.Add(dcinitial);
          DataRow dr = dt.NewRow();
          dr[0]=paramValue;
          dt.Rows.Add(dr);
          ReportDocument oRpt = new ReportDocument();            
         string path = Server.MapPath("~/PDFDocs/crystalreport.rpt");
        oRpt.Load(path);
        oRpt.SetDataSource(dt);



        MemoryStream oStream = new MemoryStream();
        oStream = (MemoryStream)oRpt.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
        Response.Clear();
        Response.Buffer = true;
        Response.ContentType = "application/pdf";
        string fileName = "Report";            
        Response.AppendHeader("content-disposition", "attachment; filename=" + fileName);                       
        Response.BinaryWrite(oStream.ToArray());
        Response.End();
        return View();
    }

Thanks

tereško
  • 58,060
  • 25
  • 98
  • 150
dsi
  • 3,199
  • 12
  • 59
  • 102

1 Answers1

0

Don't write to the Response in the controller. Aside from coupling issues and testability, it's confusing the functionality of that controller action. This code is trying to both write the file to the response and return the view.

Instead, just return the file, which you can do directly from the stream:

return File(oStream, "application/pdf", fileName);

However...

I do AJAX call

That's going to complicate things a bit. Ideally this wouldn't be an AJAX call. This is because AJAX doesn't handle "files" in a way you might think. There are options, but it would probably be easier to make this a normal page-level request so the browser can handle the file natively.

Since it's returning a file and not a view, the browser won't unload the current page. (Unless it's configured to display the file instead of save it, though there isn't much you can do about that. The server-side code is properly suggesting that the browser save the file by providing a Content-Disposition header.)

Community
  • 1
  • 1
David
  • 208,112
  • 36
  • 198
  • 279
  • ok, will it be fine even though, i call this action using AJAX ? – dsi Oct 18 '14 at 13:11
  • @Dhaval: I just added some more details to the answer around that :) The short version is that you *might* be able to handle a file download through AJAX (likely with the use of a plugin somewhere), but ideally it wouldn't be an AJAX call. – David Oct 18 '14 at 13:14