How to Open PDF Files in Web Brower 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#.

Visual Studio 2012

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

Complete Program

CreateZip.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Open_PDF.aspx.cs" Inherits="Open_PDF" %>  
<!DOCTYPE html>  
<html xmlns="http://www.w3.org/1999/xhtml">  
<head runat="server">  
    <title></title>  
</head>  
<body>  
    <form id="form1" runat="server">  
        <h3 style="color: #0000FF">Open PDF files using ASP.NET</h3>  
    <div>  
        <asp:Button ID="bttnpdf" runat="server" Text="Click for open PDF" Font-Bold="True" OnClick="bttnpdf_Click" />  
    </div>  
    </form>  
</body>  
</html>

Open.aspx.cs

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Web;  
using System.Web.UI;  
using System.Web.UI.WebControls;  
using System.Net;  
public partial class Open_PDF : System.Web.UI.Page  
{  
    protected void Page_Load(object sender, EventArgs e)  
    {  
    }  
    protected void bttnpdf_Click(object sender, EventArgs e)  
    {  
        string FilePath = Server.MapPath("javascript1-sample.pdf");  
        WebClient User = new WebClient();  
        Byte[] FileBuffer = User.DownloadData(FilePath);  
        if (FileBuffer != null)  
        {  
            Response.ContentType = "application/pdf";  
            Response.AddHeader("content-length", FileBuffer.Length.ToString());  
            Response.BinaryWrite(FileBuffer);  
        }  
    }  
}

Output 

 open a PDF file using ASP.NET

Click on the button.

 open a PDF file using ASP.NET

For more information, download the attached sample application.


Similar Articles