Surya
Surya

Reputation: 157

How To Open PDF Files In New Tab In Browser Using GridView Row Command In ASP.NET C#

i am trying to open PDF file in new Tab in browser, but its open same Tab.. iam using gridview Template field to open pdf..

How To Open PDF Files In New Tab In Browser Using GridView Row Command In ASP.NET C#

enter image description here

ASP.NET

<asp:GridView ID="gvwPDF" runat="server" CssClass="mGrid" CellPadding="20" CellSpacing="20" AutoGenerateColumns="false" EmptyDataText="No files uploaded" Width="100%">
   <Columns>
     <asp:BoundField DataField="Text" HeaderText="File Name" />
    <asp:TemplateField>
         <ItemTemplate>
           <asp:LinkButton ID="lnkRead" runat="server" Text="✉ Read" CommandName="Read" CssClass="gvwedit" ForeColor="Green" OnClick="ReadPDFFile" CommandArgument='<%# Eval("Value") %>'></asp:LinkButton>
           </ItemTemplate>
         </asp:TemplateField>
</Columns>
 </asp:GridView>

C#

protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (!IsPostBack)
            {
                string[] filePaths = Directory.GetFiles(Server.MapPath("~/Uploads/"));
                List<ListItem> files = new List<ListItem>();
                foreach (string filePath in filePaths)
                {
                    files.Add(new ListItem(Path.GetFileName(filePath), filePath));
                }
                gvwPDF.DataSource = files;
                gvwPDF.DataBind();
            }
        }
        catch (Exception ex)
        {
            //PopMsg.Pop(ex.Message.ToString(), BmGate.WebFormUserControls.Common.MessageBox.IconError, "Error");
            ScriptManager.RegisterStartupScript(this, GetType(), "Error Message", "alert('" + ex.Message.ToString() + "')", true);
        }
    }

protected void ReadPDFFile(object sender, EventArgs e)
    {
        try
        {
            string path = (sender as LinkButton).CommandArgument;
            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);
                ClientScript.RegisterClientScriptBlock(this.GetType(), "Message", "window.open('application/pdf','_blank');", true);
            }
        }
        catch (Exception ex)
        {
            ScriptManager.RegisterStartupScript(this, GetType(), "Error Message", "alert('" + ex.Message.ToString() + "')", true);
        }
    }

help to solve this issue..

Upvotes: 0

Views: 8893

Answers (3)

terbubbs
terbubbs

Reputation: 1512

In your LinkButton, set the OnClientClick to this:

<asp:LinkButton ID="lnkRead" runat="server" Text="✉ Read" CommandName="Read" CssClass="gvwedit" ForeColor="Green" OnClientClick="window.open('newPage.aspx?fileName=<%# Eval("Value") %>', '_newtab');"></asp:LinkButton>

This will open a new tab with the PDF file name as a QueryString (Other solutions for opening new tabs here). What you would want to change in your current Page_Load is making the value of the ListItem the file name so that you are not passing a file path over URL parameter.

In the Page_Load of newPage.aspx (the new tab being opened), load your pdf data. If you are receiving a Byte[] from your WebClient, this is how I write the PDF:

string fileName = Request.QueryString["fileName"];
string path = Path.Combine(Server.MapPath("~/Uploads/"), fileName);
WebClient client = new WebClient();
Byte[] buffer = client.DownloadData(path);
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader("Content-Type", "application/pdf");
HttpContext.Current.Response.AddHeader("Content-Disposition", "inline; filename=" + fileName);
HttpContext.Current.Response.BinaryWrite(buffer);
HttpContext.Current.Response.End();

Let me know if this works for you. I've tested the OnClientClick in the LinkButton and it opened a new tab successfully. Separately, I've used the Response code above in a few different pages without issue.

Upvotes: 3

Peter B
Peter B

Reputation: 24136

I see you are already trying to set the target to _blank, but not until the PDF is being constructed, which is too late. It has to be done in the page that has the LinkButtons.

Try using the GridView_RowDataBound event of gvwPDF to modify the LinkButtons, something like this:

var linkButton = e.Row.FindControl("lnkRead");
linkButton.Attributes.Add("target", "_blank");

Upvotes: 0

bdn02
bdn02

Reputation: 1500

Try to add a content-disposition header:

Response.AddHeader("content-disposition", "attachment;filename=sample1.pdf");

Upvotes: -1

Related Questions