【问题标题】:How to Open the PDF file in new tab using c#?如何使用 c# 在新选项卡中打开 PDF 文件?
【发布时间】:2015-09-30 09:39:15
【问题描述】:

在这里,我在浏览器的新选项卡中打开选定的 PDF 文件时遇到问题。下面是我完成的代码。任何人都可以帮助我...请...

搜索按钮:

protected void Button1_Click(object sender, EventArgs e)
                {
                    ListBox1.Items.Clear();
                    string search = TextBox1.Text;
                    if (TextBox1.Text != "") 
                    {
                        string[] pdffiles = Directory.GetFiles(@"\\192.168.5.10\fbar\REPORT\CLOTHO\H2\REPORT\","*"+ TextBox1.Text + "*.pdf", SearchOption.AllDirectories);

                        foreach (string file in pdffiles)
                        {
              ListBox1.Items.Add(new ListItem(Path.GetFileName(file), file));
                        }
                    }
                    else
                    {
    Response.Write("<script>alert('For this Wafer ID Report is Not Generated');</script>");
                    }
                }

PDF文件打开按钮:

            protected void Button2_Click(object sender, EventArgs e)
            {
                    try
                    {
                    string fileName = ListBox1.SelectedValue;
                    byte[] fileBytes = System.IO.File.ReadAllBytes(fileName);

                    WebClient User = new WebClient();
                    Byte[] FileBuffer = User.DownloadData(fileName);
                    if (FileBuffer != null)
                    {
             Response.ContentType = "application/pdf";
             Response.AddHeader("content-length", FileBuffer.Length.ToString());
             Response.BinaryWrite(FileBuffer);
                    }
                    }
                        catch(Exception ex)
                            {
         Response.Write("<script>alert('PDF File is not Selected');</script>");
                            }
                }
            }

【问题讨论】:

  • 有什么问题?是运行时问题还是编译问题?由于错误引用的字符串,您发布的代码将无法编译。你得到什么错误?
  • 没有错误。但我需要在新标签中打开 pdf 文件..你能帮帮我吗..
  • 这段代码会在服务器上运行,所以不能直接影响浏览器。您需要在客户端打开一个目标为 _blank 的链接以打开一个新选项卡。

标签: c# vb.net pdf c#-4.0


【解决方案1】:

你需要注入一些 javascript 代码:

Response.Write("<script>window.open('" + pdf_filepath + "','_blank')</script>");

这应该可行:D

【讨论】:

  • 感谢您的代码。我可以在哪里添加代码。这是因为我如下所示。 PDF 文件无法在新选项卡中打开。请帮帮我.... 'code'{ Response.Write(""); Response.ContentType = "应用程序/pdf"; Response.AddHeader("内容长度", FileBuffer.Length.ToString()); Response.BinaryWrite(FileBuffer); }
  • 您可以创建一个特殊的 ASPX 页面来显示 pdf。例如。 “显示_pdf.aspx”。 javascript 代码将在新选项卡中打开 aspx 页面,并将 pdf 文件名附加为查询字符串。例如。 display_pdf.aspx?path=csharpfordummies.pdf display_page.aspx 将在 page_load() 方法中查找 pdf 文件,并使用上面的代码呈现它。 '代码'{ Response.ContentType = "应用程序/pdf"; Response.AddHeader("内容长度", FileBuffer.Length.ToString()); Response.BinaryWrite(FileBuffer); }
猜你喜欢
  • 1970-01-01
  • 2019-04-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-02
  • 2017-09-18
  • 1970-01-01
  • 2020-10-09
相关资源
最近更新 更多