繁体   English   中英

在代码隐藏中设置 onclick 用于 Anchor 标签下载 pdf

[英]set onclick in codebehind for Anchor tag to download pdf

我正在尝试在代码隐藏中使用锚点,并在单击该锚点时下载 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", "");

对于每个 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 中使用 c# 2.0,在 2005 年服务器中使用 sql。在后面的代码中设置 onclick 真的让我脑子一团糟。 提前感谢您的帮助!!

如果你想让 pdf 在浏览器中可见,试试这个

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

如果你想下载 pdf,你可以创建一个内容类型响应设置为 application/pdf 的 ashx web 服务作为响应,然后从那里下载它。 然后应该会出现下载 window。

这是一个有用的线程的链接:

如何强制自动下载 pdf?

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

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

    container.Controls.Add(apdf);      

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

试试这个,让我知道进展如何。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM