Skip to content

Instantly share code, notes, and snippets.

@bjcull
Created January 30, 2014 03:52
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save bjcull/8702230 to your computer and use it in GitHub Desktop.
Save bjcull/8702230 to your computer and use it in GitHub Desktop.
A Filter Attribute that lets you download an ASP.NET MVC View as a Word Document
public class WordDocumentAttribute : ActionFilterAttribute
{
public string DefaultFilename { get; set; }
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
var result = filterContext.Result as ViewResult;
if (result != null)
result.MasterName = "~/Views/Shared/_LayoutWord.cshtml";
filterContext.Controller.ViewBag.WordDocumentMode = true;
base.OnActionExecuted(filterContext);
}
public override void OnResultExecuted(ResultExecutedContext filterContext)
{
var filename = filterContext.Controller.ViewBag.WordDocumentFilename;
filename = filename ?? DefaultFilename ?? "Document";
filterContext.HttpContext.Response.AppendHeader("Content-Disposition", string.Format("filename={0}.doc", filename));
filterContext.HttpContext.Response.ContentType = "application/msword";
base.OnResultExecuted(filterContext);
}
}
@LjupcoKostic
Copy link

LjupcoKostic commented May 8, 2016

Great article,how can be modified this for pdf document and how can i choose download folder?

@jbnkrn
Copy link

jbnkrn commented Jan 25, 2017

After generating word document, if there is a apostrophe in a word then it render as ’ . Can you help me to fix this issue. Thanks in advance.

@xtinne
Copy link

xtinne commented Mar 22, 2017

Is there a possibility to give it a custom CSS? He can't find the css files from my project.

@chinhvo
Copy link

chinhvo commented May 18, 2018

thank useful code 💃

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment