Wednesday, March 28, 2012

How to force a pdf file to download ASP.NET

If you try to open pdf files on a browser, those are automatically open but if you need to force the browser to directly download the pdf instead you have to add file header and give the full path. see the example:


<span style="color:red">Click <a href="download.aspx"
target="_blank"><u> here </u></a> to download resume.</span>



then on the page load method of the download.aspx page, write this:

Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
Response.Clear()
Response.AddHeader("content-disposition", "attachment;filename=documents/resume.pdf")
Response.ContentType = "application/pdf"      Response.WriteFile(Server.MapPath("~/documents/resume.pdf"))
Response.[End]()
End Sub


Happy Coding!!