Pergunta

I am using Rotativa tool to display pdf. It works fine with the following code:

public ActionResult PreviewDocument()
{

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

I wanted to know the way to download the pdf via browser's "save as" dialog on clicking on a button and not to display in some iframe. "new ViewAsPdf(model)" just returns the pdf data.

Thanks in advance.

Foi útil?

Solução

You can add additional attributes to the Rotativa call like this:

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

And it'll create the file for you. :)

Outras dicas

I finally got a way to do this.

Actually rotativa's method "return new ViewAsPdf(model)" returns HttpResponseStream. Where we can hardly do something. But we can modify/alter the response once the action get executed by using custom attribute. We can override OnResultExecuted() method of action filter.

Controller's action

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

Custom Action filter:

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

You can use return new ActionAsPdf. No custom attributes or anything else required. Example: 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);
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top