简体   繁体   中英

How to open pdf file in new tab Asp.net

I'm trying to open pdf file in new tab as well as give a message pop up saying that the transaction was completed. However at the moment it opens in the same tab for ie, chrome and firefox browsers and microsoft edge opens up the pdf. I have this successful message that it doesn't popup : Page.ClientScript.RegisterStartupScript(typeof(Page), "MessagePopUp", "alert('Transaction completed successfully'); window.location.href = 'LoadSheet.aspx';", true); This is what I have so far.

   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();

            }

You'll have to call window.open('LoadSheet.aspx') , I use it most of the time:

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

Edit:

My approach is call a Generic Handler (ashx) and do all the job there, passing data through session variables.

VB.Net:

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

UPDATE:

I created a sample solution using Page.ClientScript.RegisterStartupScript(...) and an .ashx Generic Handler:

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 (code behind):

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 (Generic Handler):

<%@ 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;
        }
    }

}

Final result: (Animated GIF. It delays 3 to 5 seconds to start because I couldn't trim it)

在此处输入图片说明

QUICK EDIT:

If you're able to response the pdf's content then you can do it at the ashx file:

Pass the sb variable to the ashx. In your code behind:

Session["sb"] = sb;

At your handler:

<%@ 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;
        }
    }

}

I'm in a hurry so this is all I could do.

ULTIMATE EDIT

Modify your current code behind:

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();
    }
}

And add a new ASPX file where you will do your PDF process, you should not have trouble with sessions and libraries.

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM