1

I am trying to use anchor in codebehind and download a pdf when that anchor is clicked. I have downloading stuff working fine on pageload, but i am not sure how to set onlick to download for 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", "");

for each onclick, i have to set the below code, so the pdf gets download only on click.

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

UPDATE :

 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 "";
}

using this opens on pageload, not on Onclick. Want to download only when the user clicks.

I am using c# 2.0 in VS 2005 and sql server 2005. setting onclick in code behind is really a mess in my head. Thank you in advance for the help!!

4

2 回答 2

1

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

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

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

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

如何强制自动下载pdf?

于 2012-04-09T23:07:26.743 回答
0

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

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

    container.Controls.Add(apdf);      

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

试试这个,让我知道它是怎么回事。

于 2012-04-10T08:01:28.703 回答