how to open pdf file in browser in new tab

Last Reply one year ago By Indresh

Posted one year ago

 

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class texting : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

        string JobCategory = Page.RouteData.Values["job_category"].ToString();
        string JobName = Page.RouteData.Values["job_name"].ToString();
        //string JobName = Request.QueryString["job_name"];
        if (!string.IsNullOrWhiteSpace(JobName))
        {
            ShowDetails(JobName);
        }


    }
    private void ShowDetails(string JobName)
    {
        SqlDataSourcejobdetails.SelectCommand = "SELECT * FROM [latestsarkarijobdb].[dbo].[TBL_jobdetails] where job_name ='" + JobName + "' ";
    }

    protected void DownloadFile(object sender, EventArgs e)
    {
        
        string JobName = Page.RouteData.Values["job_name"].ToString();
        byte[] bytes;
        string fileName, contentType;
        string constr = ConfigurationManager.ConnectionStrings["abc"].ConnectionString;
        using (SqlConnection con = new SqlConnection(constr))
        {
            using (SqlCommand cmd = new SqlCommand())
            {
                cmd.CommandText = "select notification_name, notification_data, notification_type from TBL_jobdetails where job_name=@job_name";
                cmd.Parameters.AddWithValue("@job_name", JobName);
                cmd.Connection = con;
                con.Open();
                using (SqlDataReader sdr = cmd.ExecuteReader())
                {
                    sdr.Read();
                    bytes = (byte[])sdr["notification_data"];
                    contentType = sdr["notification_type"].ToString();
                    fileName = sdr["notification_name"].ToString();
                }
                con.Close();
            }
        }
        Response.Clear();
        Response.Buffer = true;
        Response.Charset = "";
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.ContentType = contentType;
        Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
        Response.BinaryWrite(bytes);
        Response.Flush();
        Response.End();
    }


}

my code is working but this is directly download not open in new tab so please help  me in this code

Posted one year ago
Hi @manishpand,
Please try the following

Open PDF File in New Window or New Tab on Button click in ASP.Net

It might help you.

Cheers Andrea.

Posted one year ago Modified on one year ago

Hi manishpand,

I have created sample code which fullfill requirement

HTML

  <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
            <Columns>
                <asp:BoundField DataField="Name" HeaderText="File Name" />
                <asp:TemplateField ItemStyle-HorizontalAlign="Center">
                    <ItemTemplate>
                        <asp:LinkButton ID="lnkView" runat="server" Text="View" OnClick="View" CommandArgument='<%# Eval("Id") %>'></asp:LinkButton>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>

C#

 private void BindGrid()
    {
        string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        using (SqlConnection con = new SqlConnection(constr))
        {
            using (SqlCommand cmd = new SqlCommand())
            {
                cmd.CommandText = "SELECT Id, Name FROM tblFiles";
                cmd.Connection = con;
                con.Open();
                GridView1.DataSource = cmd.ExecuteReader();
                GridView1.DataBind();
                con.Close();
            }
        }
    }
 protected void View(object sender, EventArgs e)
    {
        string url = string.Format("Default.aspx?Id={0}", (sender as LinkButton).CommandArgument);
        string script = "<script type='text/javascript'>window.open('" + url + "')</script>";
        this.ClientScript.RegisterStartupScript(this.GetType(), "script", script);
    }

Second Page:

HTML

        <div>
            <asp:Literal ID="ltEmbed" runat="server" />
        </div>

C#

protected void Page_Load(object sender, EventArgs e)
{
    string embed = "<object data=\"{0}{1}\" type=\"application/pdf\" width=\"500px\" height=\"300px\">";
    embed += "If you are unable to view file, you can download from <a href = \"{0}{1}&download=1\">here</a>";
    embed += " or download <a target = \"_blank\" href = \"http://get.adobe.com/reader/\">Adobe PDF Reader</a> to view the file.";
    embed += "</object>";
    ltEmbed.Text = string.Format(embed, ResolveUrl("~/FileCS.ashx?Id="), Request.QueryString["Id"]);
 }

Add Handler

public void ProcessRequest(HttpContext context)
{
    int id = int.Parse(context.Request.QueryString["Id"]);
    byte[] bytes;
    string fileName, contentType;
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand())
        {
            cmd.CommandText = "SELECT Name, Data, ContentType FROM tblFiles WHERE Id=@Id";
            cmd.Parameters.AddWithValue("@Id", id);
            cmd.Connection = con;
            con.Open();
            using (SqlDataReader sdr = cmd.ExecuteReader())
            {
                sdr.Read();
                bytes = (byte[])sdr["Data"];
                contentType = sdr["ContentType"].ToString();
                fileName = sdr["Name"].ToString();
            }
            con.Close();
        }
    }

    context.Response.Buffer = true;
    context.Response.Charset = "";
    if (context.Request.QueryString["download"] == "1")
    {
        context.Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
    }
    context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
    context.Response.ContentType = "application/pdf";
    context.Response.BinaryWrite(bytes);
    context.Response.Flush();
    context.Response.End();
}

public bool IsReusable
{
    get
    {
        return false;
    }
}

I hope help you.

I agree, here is the link: https://www.e-iceblue.com/Introduce/spire-office-for-net-free.html