本文主要介绍了asp.net mvc项目实现直接预览pdf文件的方法,具有很好的参考价值,下面跟着小编一起来看下吧
背景及需求
项目使用的是mvc4框架,其中有一个功能是根据设置生成pdf文件,并在点击时直接预览。
实现过程
1、第一版实现代码:
html内容
@{
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>
控制器代码
public actionresult getpdf()
{
return new filepathresult("~/content/the garbage collection handbook.pdf", "application/pdf");
}
缺点:标题和文件下载时名称不是很友好。
1、第二版实现代码:
我们做了2件事情:
1、让下载弹出框能显示友好的下载文件名。
2、让浏览器中的其他两个显示getpdf的地方也显示友好的内容。
自定义actionfilter,对header进行修改,变为内联。(直接这么替换不知道会不会有隐患。)
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);
}
}
}
自定义actionnameselector实现对action名称的拦截和判断。
public class myactionnameselecter : actionnameselectorattribute
{
public override bool isvalidname(controllercontext controllercontext, string actionname, methodinfo methodinfo)
{
return actionname.contains("-pdf文件预览");
}
}
控制器内代码修改如下
[myactionnameselecter]
[mypdfactionfilter]
public actionresult getpdf()
{
return new filepathresult("~/content/the garbage collection handbook.pdf", "application/pdf")
//增加filedownloadname设置,但是这会让内容以附件的形式响应到浏览器(具体参考文件响应模式:内联和附件)。
//文件变成被浏览器下载。
{ filedownloadname = "the garbage collection handbook.pdf" };
}
页面内容修改如下
@{
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>
最终效果
【相关推荐】
1. asp.net免费视频教程
2. asp.net教程
3. 极客学院asp.net视频教程
以上就是asp.net mvc 设置生成pdf文件,并可以点击预览的详细内容。