Вам нужно будет позвонить 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;
}
}
}
Я спешу, так что это все, что я мог сделать.
ULTIMATE EDIT
Измените свой текущий код:
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();
}