Force browser to download PDF instead of opening it in ASP.Net

rakeshkuma
 
on Dec 08, 2020 05:46 AM
3603 Views

Forcefully download pdf file instead of opening in browser in asp.net

I have trtied all below codes but none of theme working.

    Protected Sub btnforcedownload_Click(sender As Object, e As EventArgs)
        Try
	    'Dim file As String = "1152.pdf"
            'Response.Clear()
            'Response.ContentType = "application/pdf"
            'Response.AppendHeader("content-disposition", "attachment; filename=1152.pdf")
            'Response.TransmitFile(file)
            'Response.End()

            Dim filename As String = "docs\1152.pdf"
            Response.ContentType = "image/pdf"
            Dim headerValue As String = String.Format("attachment; filename={0}", filename)
            Response.AppendHeader("Content-Disposition", headerValue)
            Response.TransmitFile(Server.MapPath(filename))
            Response.[End]()

            'Response.AddHeader("Content-Disposition", "attachment; filename=1152.pdf")
            'Response.WriteFile(Server.MapPath(Request.QueryString("File")))

            'Dim filename As String = "docs\1152.pdf"
            'Response.ContentType = "image/pdf"
            'Dim headerValue As String = String.Format("attachment; filename={0}", filename)
            'Response.AppendHeader("Content-Disposition", headerValue)
            'Response.TransmitFile(Server.MapPath(filename))
            'Response.End()

            'Dim strURL As String = "docs\1152.pdf"
            'Dim req As WebClient = New WebClient
            'Dim response As HttpResponse = HttpContext.Current.Response
            'response.Clear()
            'response.ClearContent()
            'response.ClearHeaders()
            'response.Buffer = True
            'response.AddHeader("Content-Disposition", "attachment;filename=1152.pdf")
            'Dim data() As Byte = req.DownloadData(Server.MapPath(strURL))
            'response.BinaryWrite(data)
            'response.End()

            'Dim obj As FileInfo = New FileInfo("docs\1152.pdf")
            'Response.Clear()
            'Response.AddHeader("Content-Disposition", "_blank;filename=1152.pdf")
            'Response.ContentType = "application/adobe"
            'Response.WriteFile(obj.FullName)
            'Response.Flush()
            'Response.End()
			
	Catch ex As Exception
            lbltestRowIndex.Text = ex.ToString
        End Try
    End Sub

 

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Dec 08, 2020 06:04 AM

Hi rakeshkuma,

Use this code.

Dim file As String = "docs\1152.pdf"
Response.Clear()
Response.ContentType = "application/pdf"
Response.AddHeader("content-disposition", "attachment;filename=1152.pdf")
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.WriteFile(Server.MapPath(file))
Response.End()