How to view PDF file on browser using asp.net c#

Many times we want to open /view PDF file on browser. Like we want to show eBook or any form in our browser before the download .so this code definitely helps you.


Design:-





Source Code:-
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="pdf.aspx.cs" Inherits="pdf" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <fieldset style="width:250px;">
            <legend>how to open/view PDF file</legend>
            <asp:Button ID="btnviewpdf" runat="server" Text="View e-book" Width="200px"
                onclick="btnviewpdf_Click" />
        </fieldset>
    </div>
    </form>
</body>
</html>





Code behind(c#)
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 pdf : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void btnviewpdf_Click(object sender, EventArgs e)
    {

        string FilePath = Server.MapPath("piyushsir.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);
        }
    }
}

Out-put:-

  
How to view PDF file on browser using asp.net c# How to view PDF  file on browser using asp.net c# Reviewed by NEERAJ SRIVASTAVA on 11:57:00 AM Rating: 5

1 comment:

Powered by Blogger.