![](/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.