How to open PDF files in web brower using asp.net?

Asp.net open PDF file in web browser using C#.

I have a simple solution is like below:

First create one new website and add one of your existing pdf file to your website after that open Default.aspx page and write the following code.

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Open PDF File in Web Browser in asp.net</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="btnOpen" Text="1st Show PDF In Browser" Font-Bold="true" runat="server" onclick="btnOpen_Click" />
<asp:Button ID="btnpdf" Text="2nd Show PDF In Browser" Font-Bold="true" runat="server" onclick="btnpdf_Click" />
</div>
</form>
</body>
</html>

Open Default.aspx.cs file and add following namespace:

using System;

using System.Net;

After added namespace write the following code:


protected void Page_Load(object sender, EventArgs e)
{
}
// First Way to show PDF in browser

protected void btnOpen_Click(object sender, EventArgs e)
{
Response.Redirect("SiteAnalytics.pdf");
}

protected void btnpdf_Click(object sender, EventArgs e)
{
string path = Server.MapPath("SiteAnalytics.pdf");
WebClient client = new WebClient();
Byte[] buffer = client.DownloadData(path);

if (buffer != null)
{
Response.ContentType = "application/pdf";
Response.AddHeader("content-length", buffer.Length.ToString());
Response.BinaryWrite(buffer);
}
}

Hope it help you better:

About the Author

avatar