How to Open PDF Files in Web Brower Using ASP.NET

In this article, I will explain how to open a PDF file in a web browser using ASP.NET.

Introduction

In this article, I will explain how to open a PDF file in a web browser using ASP.NET.

Use the following procedure.

Step 1

Open Visual Studio 2012 and click "File" -> "New" -> "web site...". A window is opened. In this window, click "Empty Web Site Application" under Visual C#.

application-name.jpg

Give the name of your application as "Open_PDF" and then click "Ok".

Step 2

After this session the project has been created, A new window is opened on the right side. This window is called the Solution Explorer. Solution Explorer contains the pdf file, css file and aspx files and looks like this:

 solution-explorer.jpg

Complete Program

CreateZip.aspx

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Open_PDF.aspx.cs" Inherits="Open_PDF" %>  
  2. <!DOCTYPE html>  
  3. <html xmlns="http://www.w3.org/1999/xhtml">  
  4. <head runat="server">  
  5.     <title></title>  
  6. </head>  
  7. <body>  
  8.     <form id="form1" runat="server">  
  9.         <h3 style="color: #0000FF">Open PDF files using ASP.NET</h3>  
  10.     <div>  
  11.         <asp:Button ID="bttnpdf" runat="server" Text="Click for open PDF" Font-Bold="True" OnClick="bttnpdf_Click" />  
  12.     </div>  
  13.     </form>  
  14. </body>  
  15. </html>  
Open.aspx.cs
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.UI;  
  6. using System.Web.UI.WebControls;  
  7. using System.Net;  
  8. public partial class Open_PDF : System.Web.UI.Page  
  9. {  
  10.     protected void Page_Load(object sender, EventArgs e)  
  11.     {  
  12.     }  
  13.     protected void bttnpdf_Click(object sender, EventArgs e)  
  14.     {  
  15.         string FilePath = Server.MapPath("javascript1-sample.pdf");  
  16.         WebClient User = new WebClient();  
  17.         Byte[] FileBuffer = User.DownloadData(FilePath);  
  18.         if (FileBuffer != null)  
  19.         {  
  20.             Response.ContentType = "application/pdf";  
  21.             Response.AddHeader("content-length", FileBuffer.Length.ToString());  
  22.             Response.BinaryWrite(FileBuffer);  
  23.         }  
  24.     }  
  25. }  
Output 1

 first-image.jpg

Click on the button.

Output 2

 final-image.jpg

For more information, download the attached sample application.