2012-04-09 87 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