欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

ASP.NET MVC 项目直接预览PDF文件

程序员文章站 2022-07-18 15:17:54
背景及需求 项目使用的是mvc4框架,其中有一个功能是根据设置生成pdf文件,并在点击时直接预览。 实现过程 1、第一版实现代码: html内容 @{...

背景及需求

项目使用的是mvc4框架,其中有一个功能是根据设置生成pdf文件,并在点击时直接预览。

实现过程

1、第一版实现代码:

html内容

@{
 layout = null;
}

<!doctype html>
<html>
<head>
 <meta name="viewport" content="width=device-width" />
 <title>index</title>
</head>
<body>
 <div> 
 @html.actionlink("预览pdf","getpdf",null,new { target="_blank"})
 </div>
</body>
</html>

控制器代码

 public actionresult getpdf()
 {
  return new filepathresult("~/content/the garbage collection handbook.pdf", "application/pdf");
 }

缺点:标题和文件下载时名称不是很友好。

ASP.NET MVC 项目直接预览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>
 <div> 
 @* 第二个参数可能是一个动态生成的内容,需要action中增加名称选择拦截,所以自定义了一个actionnameselectorattribute类满足要求。 *@
 @html.actionlink("预览pdf", "the garbage collection handbook-pdf文件预览", null,new { target="_blank"})
 </div>
</body>
</html>

最终效果

ASP.NET MVC 项目直接预览PDF文件

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持!