如何在MVC中打开生成的PDF

时间:2014-10-18 12:54:47

标签: ajax asp.net-mvc asp.net-mvc-4

我执行AJAX调用以从水晶报告中生成PDF。

问题是,如何直接打开PDF。

以下是我的内容。看起来,pdf已创建,但它只是返回查看而无法打开PDF。

请指导我。

代码:

      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();
    }

由于

1 个答案:

答案 0 :(得分:0)

不要写入控制器中的Response。除了耦合问题和可测试性之外,它还混淆了控制器操作的功能。此代码尝试文件写入响应返回视图。

相反,只需返回文件,您可以直接从流中执行此操作:

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

...然而

  

我做AJAX调用

这会使事情变得复杂一些。理想情况下,不会是一个AJAX调用。这是因为AJAX没有处理"文件"在某种程度上你可能会想到。 There are options,但这可能更容易使这成为正常的页面级请求,因此浏览器可以本地处理该文件。

由于它返回的是文件而不是视图,因此浏览器无法卸载当前页面。 (除非它被配置为显示文件而不是保存它,尽管你无法做到这一点。服务器端代码正确地建议浏览器< em>通过提供Content-Disposition标题来保存文件。)