6

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

提前致谢。

4

3 回答 3

11

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

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

它会为你创建文件。:)

于 2015-01-06T07:37:04.823 回答
4

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

实际上 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);
    }
}
于 2013-01-09T12:23:38.550 回答
3

您可以使用返回新的 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);
}
于 2013-10-01T14:31:48.493 回答