使用SaveAs对话框下载Rotativa

时间:2013-01-07 13:47:44

标签: asp.net-mvc rotativa

我正在使用Rotativa工具来显示pdf。使用以下代码可以正常工作:

public ActionResult PreviewDocument()
{

     var htmlContent = Session["html"].ToString();
     var model = new PdfInfo { Content = htmlContent, Name = "PDF Doc" };
     return new ViewAsPdf(model);
}

我想知道在点击按钮时通过浏览器的“另存为”对话框下载pdf的方式,而不是在某些iframe中显示。 “new ViewAsPdf(model)”只返回pdf数据。

提前致谢。

3 个答案:

答案 0 :(得分:7)

您可以向Rotativa调用添加其他属性,如下所示:

return new PartialViewAsPdf("PreviewDocument", pdfModel)
                   {
                       PageSize = Size.A4,
                       FileName = "PDF Doc.pdf"
                   };

它会为您创建文件。 :)

答案 1 :(得分:4)

我终于有办法做到这一点。

实际上,rotativa的方法“返回新的ViewAsPdf(模型)”返回HttpResponseStream。在哪里我们几乎无法做某事。但是,一旦使用自定义属性执行操作,我们就可以修改/更改响应。我们可以覆盖OnResultExecuted()方法的动作过滤器。

控制人员的行动

[HttpGet]
[ActionDownload] //here a custom action filter added
public ActionResult DownloadDocument()
{   
    var htmlContent = "<h1>sachin Kumar</hi>";

    var model = new PdfInfo {FtContent = htmlContent, FtName = "Populate Form"};
    return new ViewAsPdf(model);
}

自定义操作过滤器:

public class ActionDownloadAttribute : ActionFilterAttribute
{
    public override void OnResultExecuted(ResultExecutedContext filterContext)
    {   
            //Add content-disposition header to response so that browser understand to download as an attachment.   
        filterContext.HttpContext.Response.AddHeader("content-disposition", "attachment; filename=" + "Report.pdf"); 

            base.OnResultExecuted(filterContext);
    }
}

答案 2 :(得分:3)

您可以使用return new ActionAsPdf。没有自定义属性或任何其他要求。 示例:https://github.com/webgio/Rotativa/

public ActionResult PrintPreviewDocument()
{
    return new ActionAsPdf("PreviewDocument") { FileName = "PDF Doc.pdf" };
}

public ActionResult PreviewDocument()
{

    var htmlContent = Session["html"].ToString();
    var model = new PdfInfo { Content = htmlContent, Name = "PDF Doc" };
    return View(model);
}
相关问题