本文转自:http://www.codeproject.com/Tips/697733/Display-PDF-within-web-browser-using-MVC

Introduction

I will demonstrate you different way to display PDF within browser using  MVC3.

Background

I have created MVC3 empty project. I have added Controller name Home and created action name Index. I have added Index view for index action. I have added Temp.pdf in my solution.

Using the code

Method 1:- Display PDf by filePath. Let's create action name DispalyPDF in Home controller as fellow and add view for action.

public FileResult DisplayPDF()
{return File("/Temp.pdf", "application/pdf"); }

That's it you can able to view PDF in browser.

I have use File function as my return type which return FileResult having overload File(filePaht,contentType).

filePath: Define the path of file. I have file in my root directory name Temp.pdf. I have define my file path as "/Temp.pdf".

contentType: Define the type of file we are returning. If the content type is supported by browser browser will display that file.

I have specified link in the Index view that will navigate to the action DisplyaPDF().

<li>@Html.ActionLink("Viw Temp PDF Method1","DisplayPDF")</li>

Method 2:- Display PDF by fileContent. Let's create action PDFDispaly() as fellow and add view PDFDisplay.

public FileResult PDFDisplay()
{string filepath = Server.MapPath("/Temp.pdf");byte[] pdfByte = Helper.GetBytesFromFile(filepath);return File(pdfByte, "application/pdf"); }

I have use File function as return type having overload File(fileContent,fileContentType)

fileContent : define file content as the byte array.

fileContentType: define the type of file eg pdf, excel, text etc..

I have use server.MapPath method to get actual path of file on server by specifying virtual path as argument. I have created Helper method name GetByetsFromFile that will return fileContent as byte array by accepting actual file path as argument.

public static byte[] GetBytesFromFile(string fullFilePath){//this method is limited to 2^32 byte files (4.2 GB) FileStream fs = null; try { fs = File.OpenRead(fullFilePath); byte[] bytes = new byte[fs.Length]; fs.Read(bytes, 0, Convert.ToInt32(fs.Length)); return bytes; } finally { if (fs != null) { fs.Close(); fs.Dispose(); } } }

Method3:- Download PDF File Let's add another link that will provide to download Temp.pdf on ClientSide.

<li>@Html.ActionLink("Download Temp PDF","PDFDownload")</li>

Let's create action name PDFDownload that will allow user to download PDF.

public FileResult PDFDownload()
{string filepath =Server.MapPath("/Temp.pdf");byte[] pdfByte = Helper.GetBytesFromFile(filepath);return File(pdfByte, "application/pdf", "demoform1"); }

I have use File function as my return type where overload  accept the fileContent, contentType and fileDownloadName.

fileDownloadName: we just need to specify the file download name where MVC3 engine will do all the magic for us and download the file on client side with the specified name.

Method4:- Display PDF File as PartialView. You can not specify the return type File as PartialViewResult. Let's use the HTML 5 tag embed in partialview to display pdf within browser and render the partial view inside div using AJax.ActionLink helper.

Let's add another actionlink on Index View but this time we will add ajax.actionlink().

<li>@Ajax.ActionLink("Viw Temp PDF Method4", "PDFPartialView", new AjaxOptions { UpdateTargetId = "pdfContainer" })</li>

Let's create action method PDFPartialView inside Home controller that return partialviewresult as fellow.

public PartialViewResult PDFPartialView()
{return PartialView();
}

Add view by checking create partial view check box. We have created partial view PDFPartialView. Create embed html 5 tag inside the partial view. Specify src to the relative path of the PDF file as fellow.

<h4>Partial View That display PDF....</h4><br /><embed src="/Temp.pdf" type="application/pdf"></embed>

Click on the link "View Temp pdf method3". You will notice pdf loaded inside the div id pdfContainer.

Method5:- Display PDF as 64 bit string. This method only work with Chrome browser. We will follow following 3 step process.

Step 1 Convert PDF into the 64 bit array.

Step 2 Convert 64 bit array into 64 bit string.

Step3 Display 64 bit string as Src of the embed tag.

Note:- Do not forget to specify mime type as type.(e.g. "image/png")

Let's create action PDFInCrome in Home controller as follow.

//only work in the crome
public PartialViewResult PDFInCrome()
{string filepath = Server.MapPath("/Temp.pdf"); byte[] pdfByte = Helper.GetBytesFromFile(filepath); var strBase64=Convert.ToBase64String(pdfByte); PDFCrome pdfCrome = new PDFCrome(); pdfCrome.Content = string.Format("data:application/pdf;base64,{0}", strBase64); return PartialView(pdfCrome); }

Let's add partial view PDFInCrome as follow.

 @model DisplayPDFDemo.Comman.PDFCrome<embed src="@Model.Content" ></embed>

We are done with our action and view. Let's call our partial view on click of Ajax.ActionLink in our Index view.

<li>@Ajax.ActionLink("Viw Temp PDF Method5", "PDFInCrome", new AjaxOptions { UpdateTargetId = "pdfContainer" })</li>

This is end our simple demo of display PDF within web browser hope you enjoy.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

[转]Display PDF within web browser using MVC3相关推荐

  1. Csharp:user WebControl Read Adobe PDF Files In Your Web Browser

    namespace GeovinDu.PdfViewer {[DefaultProperty("FilePath")][ToolboxData("<{0}:Show ...

  2. How To Open An URL In Android’s Web Browser

    How To Open An URL In Android's Web Browser 以下核心代码片断,将展现使用"android.content.Intent" 打开一个指定的 ...

  3. RAD PDF于Web浏览器的PDF阅读器

    RAD PDF 基于Web浏览器的PDF阅读器 作为功​​能最完备的基于HTML的PDF查看器,编辑器和ASP.NET的表单填充器,提供了灵活而强大的替代常规PDF解决方案.与Adobe Acroba ...

  4. Couldn't find a suitable web browser! Set the BROWSER environment variable to your desired browser.

    简介 使用golang的pprof工具,使用时候提示 Couldn't find a suitable web browser! Set the BROWSER environment variabl ...

  5. PowerPoint 2019无法插入Microsoft Web Browser控件

    问题:PowerPoint 2019打开文件时,提示一些控件无法激活,在开发工具的控件中,选择Microsoft Web Browser显示无法插入此ActiveX控件(如图). 注:已在信任中心设置 ...

  6. PB Microsoft web browser 指定IE浏览器

    PB9 Microsoft web browser 默认是使用IE7内核,不支持H5,并且IE7都是淘汰的版本,兼容性很差,如果需要在PB9  嵌入H5,可以通过修改注册表指定PB9程序Microso ...

  7. 如何创建PDF发票Web应用程序

    目录 构建Web应用程序以创建和发送PDF发票 先决条件 创建新的Express应用程序 创建发票路由 添加视图和样式 使用Foxit生成PDF 使用Nodemailer发送电子邮件 结论 获得报酬是 ...

  8. Have your GDX app run in the web browser

    https://code.google.com/p/libgdx-users/wiki/Applets ---------------------------------------------- H ...

  9. The genius behind Google’s web browser

    崇拜,真正的世外高人(⊙o⊙)哦 ( ps:为什么国外高手都用Mac ) 书中漫画地址:看这里@google     或者 本帖后附件下载 ( 用firefox打开 ) 原文链接:The genius ...

最新文章

  1. mysql悲观锁和乐观锁
  2. DB2安全(一)——概述
  3. 构建轻量级的Table View注意事项[UIKit]
  4. #035 大数阶乘 PTA题目6-10 阶乘计算升级版 (20 分)
  5. GDCM:gdcm::Scanner的测试程序
  6. android.intent.action.view 融云,Android 融云SDK集成单聊
  7. Mssql,Access的sql经典SQL语句大全
  8. Web前端 HTTP1.0、 HTTP 1.1 、 HTTP2.0 区别与联系
  9. InnoDB存储引擎
  10. 【软件应用】word等office软件中好用的数学公式编辑器插件
  11. 机器视觉(9)搞懂机器视觉基本内容,这份PPT就够了!
  12. 报考建行考计算机专业知识资料,建设银行信息技术类考试都考什么,有没有以前......
  13. Android连接网络打印机进行打印
  14. Android中访问sdcard路径的几种方式
  15. CSAPP 第3章 机器级编程课后作业
  16. python如何爬虫股票数据_如何抓取股票数据_用Python抓取新浪的股票数据
  17. BUUCTF NewStarCTF 公开赛赛道Week3 Writeup
  18. Linux网络延迟排查方法
  19. textView 的设置文本中某一文字的字体颜色以及图文混排
  20. HashMap 和 Array 有什么区别?

热门文章

  1. GPIO代码使用流程(伪代码部分示例)
  2. ubuntu mysql的穷_Ubuntu安装配置Mysql
  3. java set删除第一个元素_Java面试题10(如何取到set集合的第一个元素)
  4. jsp中如何运行java_从上帝视角看Java如何运行
  5. Verilog设计实例(3)基于Verilog的单端口同步读写RAM设计
  6. 硬件数据手册中如何表示信号高低电平有效?
  7. 【 FPGA 】时钟抖动浅记
  8. 【 Notes 】COMPARISON OF BASIC METHODS AND POSITIONING SYSTEMS
  9. 即将上线的Hive服务器面临的一系列填坑笔记
  10. Nginx源码安装及应用