在新窗口中下载pdf而不重定向

时间:2012-09-26 16:22:01

标签: asp.net pdf-generation http-redirect

我有一个aspx页面,它有几个控件。当我点击此页面上的按钮时, 我需要获取文本框和下拉列表的值并进行一些处理并将其传递给另一个aspx页面。第二个aspx将进行进一步处理并生成pdf以供下载。 我不希望将用户重定向到第二页。我只是希望pdf下载出现在一个新窗口中。 我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:2)

您需要设置Content-Disposition http标头并直接返回pdf。

像这样:

Response.ContentType = "application/x-download";
Response.AddHeader("Content-Disposition", string.Format("attachment; filename=\"{0}\"", fileName));
Response.WriteFile(filePath + fileName);
Response.Flush();
Response.End();

注意:请勿将Content-Disposition设置为application/pdf,因为许多浏览器都会识别它,并且会尝试使用浏览器中嵌入的pdf-reader打开它。

点击按钮后如何发布到第二页?

在按钮上设置PostbackUrl,如下所示:

<asp:Button 
  ID="Button1" 
  PostBackUrl="~/TargetPage.aspx"
  runat="server"
  Text="Submit" />

您可以使用PreviousPage属性访问控件,从目标页面上的当前页面读取值,如下所示:

TextBox SourceTextBox = 
    (TextBox)Page.PreviousPage.FindControl("TextBox1");
if (SourceTextBox != null)
{
    Label1.Text = SourceTextBox.Text;
}