【问题标题】:Rotativa Download with SaveAs dialogRotativa 下载和另存为对话框
【发布时间】:2013-01-07 13:47:44
【问题描述】:

我正在使用 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 数据。

提前致谢。

【问题讨论】:

    标签: asp.net-mvc rotativa


    【解决方案1】:

    您可以像这样向 Rotativa 调用添加其他属性:

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

    它会为你创建文件。 :)

    【讨论】:

    • 为什么这不是公认的答案?它很简单,几乎不需要任何额外的代码并且工作得很好。
    • 这正是我所需要的。超级简单。谢谢。
    【解决方案2】:

    我终于找到了办法。

    其实rotativa的方法“return new ViewAsPdf(model)”返回的是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);
        }
    }
    

    【讨论】:

    • 为什么这个答案没有被称为“答案”?这对于所有使用 MVC ActionResults 来返回 PDF 文件的人来说都是有用的,而不管任何库。我正在使用 MvcRazorToPdf,它依赖于 iTextSharp,并且这段代码仍然有效。
    • 这太复杂了,看看@derekadk 的回答。您所要做的就是添加 FileName 属性: return new ViewAsPdf(model) { FileName = "file.pdf" };
    【解决方案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);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多