本文转自: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.

Hide    Copy Code
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().

Hide    Copy Code
<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.

Hide    Copy Code
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.

Hide    Copy Code
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.

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

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

Hide    Copy Code
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().

Hide    Copy Code
<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.

Hide    Copy Code
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.

Hide    Copy Code
<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.

Hide    Copy Code
//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.

Hide    Copy Code
 @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.

Hide    Copy Code
<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. Display PDF in browser | Acrobat, Reader XI

    点这个链接查看详细的解决办法 http://helpx.adobe.com/acrobat/using/display-pdf-browser-acrobat-xi.html When you cli ...

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

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

  3. 关于PB调用Microsoft Web Browser控件的一些问题

    Microsoft Web Browser控件是WINDOWS系统自带的控件,一般不需要单独安装,由于工作的需要,把使用中遇到的问题记录一下,以便查阅. 插入控件: 环境为PB12.0,insert- ...

  4. Atitit.office word  excel  ppt pdf 的web在线预览方案与html转换方案 attilax 总结

    Atitit.office word  excel  ppt pdf 的web在线预览方案与html转换方案 attilax 总结 1. office word  excel pdf 的web预览要求 ...

  5. 对于一个网站,如何禁止直接从浏览器Web browser中访问js文件

    比如有一个网站,https://testsystem.infotest.com 在这个网站的内容文件目录下面,有一个scripts文件夹,该文件夹中有一个js文件,比如lukeTest.js文件 这样 ...

  6. C#彻底解决Web Browser 跨域读取Iframes内容

    C#彻底解决Web Browser 跨域读取Iframes内容 用C# winform的控件web browser 读取网页内容,分析一下数据,做一些采集工作. 如果是同一个域名下面还是好办的,基本上 ...

  7. 教你如何清除 MyEclipse/Eclipse 中 Web Browser 和 Switch Workspace 的历史记录

    有些许强迫症的开发人员可能会因为 MyEclipse/Eclipse 中 Web Browser 和 Switch Workspace 冗余的历史记录而感到苦恼,下面的方法就可以有效的帮助解决你的痛点 ...

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

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

  9. How to open a web site with the default web browser in a NEW window

    http://delphi.about.com/cs/adptips2004/a/bltip0504_4.htm When using ShellExecute (as explained in th ...

随机推荐

  1. C#组态控件Iocomp应用案例

    Iocomp组件需要在vs2010环境下使用,目前用到的是4.04版本.在两个项目中用到了它,一个是锅炉监控系统,另一个是绝缘靴检测系统. 锅炉监测系统 这个节目基本都是使用Iocomp控件完成. 出 ...

  2. WPF画图简便技巧

    下面这个就是:起点在(0,0)开始的正方形.(用绿色填充).此方法比一条一条的写方便多了! <Path Fill="LawnGreen" Data="M 0 0 L ...

  3. Dubbo初探

    Dubbo是什么? 1.阿里巴巴开源项目.2.Dubbo是一个分布式服务框架,致力于提供高性能和透明化的RPC远程服务调用方案,以及SOA服务治理方案. ps: SOA(面相服务的体系结构) RPC( ...

  4. ahjesus不断完善的js小"内裤"

    String.prototype.isNullOrWhiteSpace = function () { /// <summary> /// 变量是undefined或者null或者空字符串 ...

  5. 关于DOM操作的性能优化

    最著名的有关用js操作dom的观点是:js和dom是独立的小岛,用桥实现两者的联系,但桥很窄,要过路费,所以我们要尽最大可能减少过桥的次数.下面代码演示了用js操作dom的innerHTML,且一下修 ...

  6. Atitit. Atiposter 发帖机 新特性 poster new feature   v7 q39

    Atitit. Atiposter 发帖机 新特性 poster new feature   v7 q39 V1  初步实现sina csdn cnblogs V2  实现qzone sohu 的发帖 ...

  7. adb 的相关操作及遇到的问题

    一. 电脑连接你的手机 1.打开手机的开发者模式 并  开启调试工具 2.用手机连接上  你的电脑 3.在eclipse 中的DDMS 中查看是否 连接到 如图所示: 这时会发现 多了一个连接 :说明 ...

  8. 异步post请求之Block方法

    #import "ViewController.h" #import "Header.h" @interface ViewController ()<NS ...

  9. 基础学习day12--多线程一线程之间的通信和常用方法

    一.线程之间的通信 1.1.线程之间的通信方法 多个线程在处理统一资源,但是任务却不同,这时候就需要线程间通信.    等待/唤醒机制涉及的方法:    1. wait():让线程处于冻结状态,被wa ...

  10. iOS--开发之手势解锁

    本文主要介绍通过手势识别实现手势解锁功能,这个方法被广泛用于手机解锁,密码验证,快捷支付等功能实现.事例效果如下所示. 首先,我们先分析功能的实现过程,首先我们需要先看大致的实现过程: 1.加载九宫格 ...