简体   繁体   English

如何在ASP.NET C#中使用GridView行命令在浏览器的新选项卡中打开PDF文件

[英]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.. 我正在尝试在浏览器的新标签页中打开PDF文件,但它会打开相同的标签页。IAM使用gridview模板字段打开pdf。

How To Open PDF Files In New Tab In Browser Using GridView Row Command In ASP.NET C# 如何在ASP.NET C#中使用GridView行命令在浏览器的新选项卡中打开PDF文件

在此处输入图片说明

ASP.NET 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# 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.. 帮助解决这个问题。

In your LinkButton, set the OnClientClick to this: 在您的LinkBut​​ton中,将OnClientClick设置为此:

<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 ). 这将打开一个新标签页,其中PDF文件名为QueryString( 此处提供其他用于打开新标签页的解决方案 )。 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. 您要在当前Page_Load中进行的更改是使ListItem的值成为文件名,以便您不会通过URL参数传递文件路径。

In the Page_Load of newPage.aspx (the new tab being opened), load your pdf data. newPage.aspxPage_Load (正在打开的新选项卡)中,加载pdf数据。 If you are receiving a Byte[] from your WebClient , this is how I write the PDF: 如果您从WebClient收到Byte[] ,这就是我编写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. 我已经在LinkButton测试了OnClientClick ,它成功打开了一个新标签页。 Separately, I've used the Response code above in a few different pages without issue. 另外,我在几个不同的页面中使用了上面的Response代码,没有出现问题。

I see you are already trying to set the target to _blank, but not until the PDF is being constructed, which is too late. 我看到您已经在尝试将目标设置为_blank,但是直到构造PDF为止,这已经太晚了。 It has to be done in the page that has the LinkButtons. 必须在具有LinkBut​​tons的页面中完成。

Try using the GridView_RowDataBound event of gvwPDF to modify the LinkButtons, something like this: 尝试使用gvwPDFGridView_RowDataBound事件来修改LinkBut​​ton,如下所示:

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

尝试添加内容处置标头:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在新选项卡或窗口中打开PDF文件,而不是使用C#和ASP.NET MVC下载它? - How to open PDF file in a new tab or window instead of downloading it using C# and ASP.NET MVC? 如何使用asp.net C#在Chrome的新标签页中打开打开的PDF - How to itextsharp PDF open in new tab in chrome using asp.net c# asp.net:如何使用c#在新窗口(不是标签页或当前页面)中打开新的asp.net页 - asp.net: How to open a new asp.net page in new window (not tab or current page) using c# 在新页面或选项卡中打开ASP.NET GridView项-如何? - Open ASP.NET GridView item in new page or tab - how to? Gridview与asp.net和C#中的下载和查看pdf文件 - Gridview with download and view pdf files in asp.net & c# 将新行数据添加到gridview asp.net c# - Add new row data to gridview asp.net c# 如何在新标签Asp.net中打开pdf文件 - How to open pdf file in new tab Asp.net 如何在新的标签页或窗口中打开PDF文件而不是下载文件(使用asp.net)? - How to open PDF file in a new tab or window instead of downloading it (using asp.net)? 使用 Asp.Net Core,如何将视图作为新的浏览器选项卡打开,然后稍后再关闭 - Using Asp.Net Core, how can I open a view as a new browser tab, and then close it again later 使用 ASP.NET 按钮、C# 和页面背后的代码在新选项卡中打开窗口 - Open Window in new tab using an ASP.NET Button, C#, and the code behind the page
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM