2012-04-09 97 views
1

我試圖在代碼隱藏中使用錨點,並單擊該錨點時下載pdf。我有下載的東西在頁面加載上工作正常,但我不知道如何設置onlick下載PDF。設置onclick在錨點標籤下載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"); 

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

使用這個打開的頁面加載,而不是的onClick。只有在用戶點擊時才需要下載。

我在VS 2005和sql server 2005中使用c#2.0。在後面的代碼中設置onclick在我頭腦中確實是一團糟。預先感謝您的幫助!

回答

0

,如果你想爲PDF在瀏覽器中

apdf.Attributes.Add( 「點擊」,「window.location.href =可以觀看試試這個 '../linktopdf/thepdf.pdf;' 「);

如果你想下載pdf,你可以創建一個ashx web服務,其內容類型響應設置爲應用程序/ pdf作爲響應,並從那裏下載它作爲byes。然後應該出現下載窗口。

這裏是一個有用的線索鏈接:

How to force a pdf download automatically?

+0

請再次看看代碼! – Ram 2012-04-09 23:38:18

0

哦,我看你現在所需要的。試試這個:

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

    container.Controls.Add(apdf);  

並確保將此代碼放在頁面的Pre_Init方法中而不是Page_load。

試試這個,讓我知道它是怎麼回事。

+0

我在按鈕的OnClick事件上有HTMLAnchor代碼。所以,每當我點擊按鈕,它正在下載PDF,但相反,我想顯示的鏈接,只有當鏈接被點擊時,PDF應該打開。我希望我明白凱文。謝謝你的時間。 – Ram 2012-04-10 18:48:07