Home > Article > Backend Development > ASP.NET MVC directly previews PDF files
Background and Requirements
The project uses the MVC4 framework. One of the functions is to generate PDF files based on settings and preview them directly when clicked.
Implementation process
1. First version implementation code:
HTML content
@{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Index</title> </head> <body> <p> @Html.ActionLink("预览PDF","GetPdf",null,new { target="_blank"}) </p> </body> </html>
##Controller code
public ActionResult GetPdf() { return new FilePathResult("~/content/The Garbage Collection Handbook.pdf", "application/pdf"); }
Disadvantages: The title and file name are not very friendly when downloaded.
1. Second version implementation code:
We did 2 things:
1. Let the download pop-up box display a friendly download file name.
2. Let the other two places in the browser that display GetPdf also display friendly content.
Customize the ActionFilter and modify the Header to become inline. (I don’t know if there will be any hidden dangers if I replace it directly like this.)
public class MyPdfActionFilter : ActionFilterAttribute { public override void OnResultExecuted(ResultExecutedContext filterContext) { //Content-Disposition=attachment%3b+filename%3d%22The+Garbage+Collection+Handbook.pdf%22} var filerHeader = filterContext.HttpContext.Response.Headers.Get("Content-Disposition"); if (!string.IsNullOrEmpty(filerHeader) && filerHeader.Substring(0, "attachment".Length).ToLower().Equals("attachment")) { filterContext.HttpContext.Response.Headers["Content-Disposition"] = "inline" + filerHeader.Substring("attachment".Length, filerHeader.Length - "attachment".Length); } } }
Customized ActionNameSelector implements Action Name interception and judgment.
public class MyActionNameSelecter : ActionNameSelectorAttribute { public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo) { return actionName.Contains("-PDF文件预览"); } }
The code in the controller is modified as follows
[MyActionNameSelecter] [MyPdfActionFilter] public ActionResult GetPdf() { return new FilePathResult("~/content/The Garbage Collection Handbook.pdf", "application/pdf") //增加FileDownloadName设置,但是这会让内容以附件的形式响应到浏览器(具体参考文件响应模式:内联和附件)。 //文件变成被浏览器下载。 { FileDownloadName = "The Garbage Collection Handbook.pdf" }; }
The page content is modified as follows
##@{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Index</title> </head> <body> <p> @* 第二个参数可能是一个动态生成的内容,需要ACTION中增加名称选择拦截,所以自定义了一个ActionNameSelectorAttribute类满足要求。 *@ @Html.ActionLink("预览PDF", "The Garbage Collection Handbook-PDF文件预览", null,new { target="_blank"}) </p> </body> </html>Final effect
For more ASP.NET MVC direct preview of PDF files related articles, please pay attention to the PHP Chinese website!