【问题标题】:How to open pdf file in new tab Asp.net如何在新标签 Asp.net 中打开 pdf 文件
【发布时间】:2018-11-05 07:43:32
【问题描述】:

我正在尝试在新选项卡中打开 pdf 文件,并弹出一条消息说交易已完成。然而,目前它在同一选项卡中打开,即 chrome 和 firefox 浏览器和 microsoft edge 打开 pdf。我有这个没有弹出的成功消息: Page.ClientScript.RegisterStartupScript(typeof(Page), "MessagePopUp", "alert('Transaction completed successfully'); window.location.href = 'LoadSheet.aspx ';", true); 这是我目前所拥有的。

   using (StringWriter sw = new StringWriter())
        {
            using (HtmlTextWriter hw = new HtmlTextWriter(sw))
            {
                StringBuilder sb = new StringBuilder();

                //Generate Invoice (Bill) Header.
                sb.Append("<table width='100%' cellspacing='0' cellpadding='2'>");

                sb.Append("<tr><td align='center' style='background-color: #18B5F0' colspan = '2'><b>Load Sheet</b></td></tr>");
                sb.Append(" </td></tr>");
                sb.Append("<br />");
                sb.Append("<br />");
                sb.Append("<br />");
                sb.Append("<br />");


                sb.Append("</td><td><b>Date: </b>");
                sb.Append(DateTime.Now);

                s

                sb.Append("</td><td><b>Username: </b>");
                sb.Append(user);

                sb.Append("</td></tr>");

                sb.Append("<tr><td ><b>Route: </b>");
                sb.Append(route);



                sb.Append("<tr><td><b>Date Order Loaded: </b>");
                sb.Append(lDate);
                sb.Append("</td></tr>");




                sb.Append("</table>");
                sb.Append("<br />");
                sb.Append("<br />");
                sb.Append("<br />");
                sb.Append("<br />");
                sb.Append("<br />");



                //Generate Dispatch Sheet Items Grid.
                sb.Append("<table border = '1'>");
                sb.Append("<tr>");
                foreach (DataColumn column in data.Columns)
                {
                    sb.Append("<th style = 'background-color: #D20B0C;color:#000000'>");
                    sb.Append(column.ColumnName);
                    sb.Append("</th>");
                }
                sb.Append("</tr>");
                foreach (DataRow row in data.Rows)
                {

                    sb.Append("<tr>");
                    foreach (DataColumn column in data.Columns)
                    {
                        sb.Append("<td>");
                        sb.Append(row[column]);
                        sb.Append("</td>");

                    }
                    sb.Append("</tr>");
                }
                sb.Append("</tr></table>");
                sb.Append("<br />");
                sb.Append("<br />");
                sb.Append("<br />");
                sb.Append("<br />");

                sb.Append("<table>");
                sb.Append("<tr><td colspan = '2'></td></tr>");
                sb.Append("<tr><td><b>Driver Name:___________________</b><br/>");
                sb.Append(driver);
                sb.Append("</tr></td>");





                Page.ClientScript.RegisterStartupScript(typeof(Page), "MessagePopUp", "alert('Transaction completed successfully'); window.location.href = 'LoadSheet.aspx';", true);


                //Export HTML String as PDF.
                StringReader sr = new StringReader(sb.ToString());
                Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
                HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
                PdfWriter writer = PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
                pdfDoc.Open();
                htmlparser.Parse(sr);
                pdfDoc.Close();
                Response.ContentType = "application/pdf";


                Response.End();

                GridView1.AllowPaging = false;
                GridView1.DataBind();

            }

【问题讨论】:

  • 您不会从服务器打开新标签页,而是在客户端打开。例如,如果用户单击链接打开此链接,请在该链接中添加 target="_blank"
  • 所以我会为要显示的 pdf 创建另一个 aspx 页面;可以举个例子吗
  • 这是我的按钮
  • 为什么需要创建另一个页面?目前尚不清楚您要做什么,但听起来您对其进行了过度设计。从所有这些代码中,甚至不清楚您是在返回实际的 PDF 还是返回 HTML。是哪个?
  • 我正在返回一个 pdf。我只是问,因为我尝试使用目标,但我不确定我是否做错了

标签: c# asp.net pdf


【解决方案1】:

你必须打电话给window.open('LoadSheet.aspx'),我大部分时间都用它:

Page.ClientScript.RegisterStartupScript(typeof(Page), "MessagePopUp", "alert('Transaction completed successfully'); window.open('LoadSheet.aspx');", true);

编辑:

我的方法是调用通用处理程序 (ashx) 并在那里完成所有工作,通过会话变量传递数据。

VB.Net:

System.Web.UI.ScriptManager.RegisterClientScriptBlock(Me, Me.[GetType](), "myFunction", "window.open('ViewDocument.ashx');", True)

更新:

我使用Page.ClientScript.RegisterStartupScript(...).ashx 通用处理程序创建了一个示例解决方案:

MyPage.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="MyPage.aspx.cs" Inherits="MyPage" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>Show me the PDF in another tab and alert me!</div>
        <asp:Button ID="btnShow" runat="server" Text="Show me!" OnClick="btnShow_Click" />
    </form>
</body>
</html>

MyPage.aspx.cs(代码隐藏):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

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

    }

    protected void btnShow_Click(object sender, EventArgs e)
    {                
        // Pass some data to the ashx handler.
        Session["myData"] = "This is my data.";

        // Open PDF in new window and show alert.
        this.Page.ClientScript.RegisterStartupScript(this.GetType(), "Alert", "window.open('ShowPDF.ashx'); alert('OK' );", true);
    }
}

ShowPDF.ashx(通用处理程序):

<%@ WebHandler Language="C#" Class="ShowPDF" %>

using System;
using System.Web;
using System.Web.SessionState; // Added manually.
using System.IO; // Added manually.

// You'll have to add 'IReadOnlySessionState' manually.
public class ShowPDF : IHttpHandler, IReadOnlySessionState {

    public void ProcessRequest (HttpContext context)  {
        // Do your PDF proccessing here.
        context.Response.Clear();
        context.Response.ContentType = "application/pdf";
        string filePath = System.Web.HttpContext.Current.Server.MapPath(@"~\docs\sample.pdf");
        context.Response.TransmitFile(filePath);

        // Show the passed data from the code behind. It might be handy in the future to pass some parameters and not expose then on url, for database updating, etc.
        context.Response.Write(context.Session["myData"].ToString());
    }

    public bool IsReusable {
        get {
            return false;
        }
    }

}

最终结果: (动画 GIF。它会延迟 3 到 5 秒才能启动,因为我无法修剪它)

快速编辑:

如果您能够response pdf 的内容,那么您可以在 ashx 文件中进行操作:

sb 变量传递给ashx。在你后面的代码中:

Session["sb"] = sb;

在您的处理程序处:

<%@ WebHandler Language="C#" Class="ShowPDF" %>

using System;
using System.Web;
using System.Web.SessionState; // Added manually.
using System.IO; // Added manually.
/* IMPORT YOUR PDF'S LIBRARIES HERE */

// You'll have to add 'IReadOnlySessionState' manually.
public class ShowPDF : IHttpHandler, IReadOnlySessionState {

    public void ProcessRequest (HttpContext context)  {
        // Do your PDF proccessing here.

        // Get sb from the session variable.
        string sb = context.Session["sb"].ToString();

                //Export HTML String as PDF.
                StringReader sr = new StringReader(sb.ToString());
                Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
                HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
                PdfWriter writer = PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
                pdfDoc.Open();
                htmlparser.Parse(sr);
                pdfDoc.Close();
                Response.ContentType = "application/pdf";


                Response.End();

    }

    public bool IsReusable {
        get {
            return false;
        }
    }

}

我很着急,所以我能做的就这些了。

终极编辑

在后面修改你当前的代码:

using (StringWriter sw = new StringWriter())
{
    using (HtmlTextWriter hw = new HtmlTextWriter(sw))
    {
        StringBuilder sb = new StringBuilder();

        //Generate Invoice (Bill) Header.

        /***
            ALL THE STRING BUILDER STUFF OMITED FOR BREVITY

            ...
        ***/            

        // Pass the sb variable to the new ASPX webform.
        Session["sb"] = sb;

        // Open the form in new window and show the alert.
        this.Page.ClientScript.RegisterStartupScript(this.GetType(), "Alert", "window.open('NewForm.aspx'); alert('Your message here' );", true);           

        GridView1.AllowPaging = false;
        GridView1.DataBind();
    }
}

并添加一个新的 ASPX 文件,您将在其中执行 PDF 处理,您应该不会遇到会话和库问题。

NewForm.aspx

protected void Page_Load(object sender, EventArgs e)
{
    // Get sb from the session variable.
    string sb = Session["sb"].ToString();

    //Export HTML String as PDF.
    StringReader sr = new StringReader(sb.ToString());
    Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
    HTMLWorker htmlparser = new HTMLWorker(pdfDoc);

    PdfWriter writer = PdfWriter.GetInstance(pdfDoc, Response.OutputStream);

    pdfDoc.Open();
    htmlparser.Parse(sr);
    pdfDoc.Close();

    Response.ContentType = "application/pdf";
    Response.End();
}

【讨论】:

    猜你喜欢
    • 2022-01-16
    • 1970-01-01
    • 2018-12-14
    • 2017-05-24
    • 1970-01-01
    • 2014-03-26
    • 1970-01-01
    • 1970-01-01
    • 2020-05-31
    相关资源
    最近更新 更多