![](/img/trans.png)
[英]How to open PDF file in a new tab or window instead of downloading it (using asp.net)?
[英]How to open pdf file in new tab Asp.net
我正在尝试在新标签页中打开pdf文件,并弹出一条消息,说明交易已完成。 但是,目前它在chrome和firefox浏览器的同一选项卡中打开,而Microsoft Edge则打开pdf。 我收到了一条不会弹出的成功消息: Page.ClientScript.RegisterStartupScript(typeof(Page),“ MessagePopUp”,“ alert('交易成功完成'); 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();
}
您必须调用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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.