ASP. net mvc project directly preview PDF files, mvcpdf
Background and requirements
The project uses the MVC4 framework. One of the functions is to generate a PDF file based on the settings and preview the file directly when you click it.
Implementation Process
1. Implementation Code of the first version:
HTML content
@ {Layout = null ;}<! DOCTYPE html>
Controller code
public ActionResult GetPdf() { return new FilePathResult("~/content/The Garbage Collection Handbook.pdf", "application/pdf"); }
Disadvantage: the title and File Download name are not very friendly.
1. Implementation Code of version 2:
We did two things:
1. Enable the download pop-up box to display friendly download file names.
2. Make the other two places in the browser display GetPdf with friendly content.
Customize the ActionFilter to modify the Header and change it to inline. (I don't know if there will be any hidden danger if I replace it 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); } } }
The custom ActionNameSelector intercepts and judges Action names.
Public class MyActionNameSelecter: ActionNameSelectorAttribute {public override bool IsValidName (ControllerContext controllerContext, string actionName, MethodInfo methodInfo) {return actionName. Contains ("-PDF file preview ");}}
Modify the code in the Controller as follows:
[MyActionNameSelecter] [MyPdfActionFilter] public ActionResult GetPdf () {return new FilePathResult ("~ /Content/The Garbage Collection handbooksucceeded "," application/pdf ") // Add The FileDownloadName setting, but this will make The content respond to The browser in The form of attachments (For details, refer to The file response mode: inner and attachment ). // The file is downloaded by the browser. {FileDownloadName = "The Garbage Collection handbooksucceeded "};}
The page content is modified as follows:
@ {Layout = null ;}<! DOCTYPE html>
Final Effect