【问题标题】:set onclick in codebehind for Anchor tag to download pdf在代码隐藏中为 Anchor 标签设置 onclick 以下载 pdf
【发布时间】:2012-04-09 22:59:30
【问题描述】:

我正在尝试在代码隐藏中使用锚点,并在单击该锚点时下载 pdf。我下载的东西在页面加载时工作正常,但我不确定如何设置 onlick 以下载 pdf。

HtmlAnchor apdf = new HtmlAnchor();
apdf.ID = Guid.NewGuid().ToString("N");
apdf.InnerText = dsreport.Tables[0].Rows[0]["ImageName"].ToString();
apdf.Attributes.Add("style", "font-weight: bold; font-size: 13px; margin: 0px;font-family: Arial; color: #1e7c9b; text-decoration: underline");
apdf.Attributes.Add("onclick", "");

对于每次点击,我必须设置下面的代码,所以 PDF 只在点击时下载。

byte[] aByteArrayOfTheFile = (byte[])(dsreport.Tables[0].Rows[0]["ImageData"]);
SendAsFileToBrowser(aByteArrayOfTheFile, "application/pdf", "downloaded.pdf");

更新:

 public static string SendAsFileToBrowser(byte[] File, string Type, string FileName)
 {
    string disp = "attachment";
    if (string.IsNullOrEmpty(FileName))
    {
        disp = "inline";
    }

    // set headers
    //char r = HttpContext.Current.Response;

    HttpContext.Current.Response.ContentType = Type; // eg "image/Png"
    HttpContext.Current.Response.Clear();
    HttpContext.Current.Response.AddHeader("Content-Type", "binary/octet-stream");
    HttpContext.Current.Response.AddHeader("Content-Length", File.Length.ToString());
    HttpContext.Current.Response.AddHeader("Content-Disposition", disp + "; filename=" + FileName + "; size=" + File.Length.ToString());
    HttpContext.Current.Response.Flush();       

    // write data to requesting browser
    HttpContext.Current.Response.BinaryWrite(File);
    HttpContext.Current.Response.Flush();
    return "";
}

使用它会在页面加载时打开,而不是在 Onclick 上。只想在用户点击时下载。

我在 VS 2005 和 sql server 2005 中使用 c# 2.0。在后面的代码中设置 onclick 真是让我头疼。提前感谢您的帮助!

【问题讨论】:

    标签: c# asp.net html


    【解决方案1】:

    如果您想在浏览器中查看 pdf,请尝试此操作

    apdf.Attributes.Add("onclick", "window.location.href='../linktopdf/thepdf.pdf;'");

    如果您想下载 pdf,您可以创建一个 ashx Web 服务,并将内容类型响应设置为 application/pdf 作为响应,然后从那里下载它作为再见。然后应该会出现下载窗口。

    这里是一个有用的帖子的链接:

    How to force a pdf download automatically?

    【讨论】:

      【解决方案2】:

      哦,我知道你现在需要什么了。试试这个:

          apdf.Click += new EventHandler(this.SendAsFileToBrowser);   
      
          container.Controls.Add(apdf);      
      

      并确保将此代码放在页面的 Pre_Init 方法中,而不是 Page_load 中。

      试试这个,让我知道结果如何。

      【讨论】:

      • 我在按钮的 OnClick 事件上有 HTMLAnchor 代码。因此,每当我单击按钮时,它正在下载 pdf,但我想显示链接,并且只有在单击链接时,才应该打开 pdf。我希望我很清楚凯文。感谢您的宝贵时间。
      猜你喜欢
      • 1970-01-01
      • 2018-08-23
      • 1970-01-01
      • 2013-04-15
      • 1970-01-01
      • 1970-01-01
      • 2014-03-03
      • 2012-09-05
      • 1970-01-01
      相关资源
      最近更新 更多