Background and requirements
The project uses the MVC4 framework, which has a feature to generate PDF files based on the settings and preview them directly when clicked.
Implementation process
1, the first version of the implementation code:
HTML content
@{Layout=NULL;}<! DOCTYPE html>"Viewport"Content="Width=device-width"/> <title>Index</title>@Html. ActionLink ("Preview PDF","getpdf",NULL,New{target="_blank"}) </div></body> Controller code
Public actionresult getpdf () { returnnew Filepathresult ("~/content/the Garbage Collection Handbook.pdf""application/pdf"); }
Cons: Title and file download when the name is not very friendly.
1, the second version of the implementation code:
We have done 2 things:
1. Allow download popup to display friendly download file name.
2, let the other two in the browser display getpdf also display friendly content.
Custom Actionfilter, modify the header to become inline. (Direct so replace do not know whether there is a hidden danger.) )
Public classMypdfactionfilter:actionfilterattribute { Public Override voidonresultexecuted (ResultExecutedContext filtercontext) {//Content-disposition=attachment%3b+filename%3d%22the+garbage+collection+handbook.pdf%22} varFilerheader = 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); } } }
Custom Actionnameselector implements the interception and judgment of the action name.
Public class Myactionnameselecter:actionnameselectorattribute { publicoverrideboolstring actionname, MethodInfo MethodInfo) { return actionname.contains ("-pdf file preview "); } }
The code in the controller is modified as follows
[Myactionnameselecter] [Mypdfactionfilter] PublicActionResult getpdf () {return NewFilepathresult ("~/content/the garbage Collection handbook.pdf","application/pdf") //add filedownloadname settings, but this will allow the content to respond to the browser in the form of an attachment (specific reference file response mode: inline and attachment). //The file becomes downloaded by the browser. {Filedownloadname ="The garbage Collection handbook.pdf" }; }
The page content is modified as follows
@{Layout=NULL;}<! DOCTYPE html>"Viewport"Content="Width=device-width"/> <title>Index</title> @* The second parameter may be a dynamically generated content that requires an action to increase the name selection interception, so a Actionnameselectorattribute class is customized to meet the requirements. *@ @Html. ActionLink ("Preview PDF","The garbage Collection handbook-pdf file preview",NULL,New{target="_blank"}) </div></body>Final effect
ASP. NET MVC Project preview PDF file directly