Friday, August 2, 2013

To retrieve the pdf stored in sql server as varbinary

Private Sub ReadPdfFromSQL()
        Try
            strConString = System.Configuration.ConfigurationManager.ConnectionStrings("CONSTRING").ConnectionString
            SqlCon = New SqlConnection(strConString)
            SqlCmd = New SqlCommand()
            SqlCmd.CommandType = CommandType.StoredProcedure
            'SqlCmd.Parameters.AddWithValue("@Type", "S")
            SqlCmd.Connection = SqlCon
            SqlCmd.CommandText = "SP_ReadPdfData"
            SqlCon.Open()
            sqldr = SqlCmd.ExecuteReader()
            Dim Buffer() As Byte = Nothing
            If sqldr.HasRows Then
                While sqldr.Read
                    Buffer = (sqldr.Item("PdfData"))
                End While
            End If
            SqlCon.Close()
            SqlCmd.Dispose()
            SqlCon.Dispose()
            'to open as an attachment
            Response.AddHeader("Content-Disposition", "attachment; filename=abc.pdf")
            Response.ContentType = "application/pdf"
            Response.BinaryWrite(Buffer)
            Response.Flush()
            Response.Close()
            Response.End()
            'to open in browser itself
            Response.ClearHeaders()
            Response.ClearContent()
            Response.ContentType = "application/pdf"
            Response.BinaryWrite(Buffer)
            Response.Flush()
            Response.Close()
            Response.End()
        Catch ex As Exception
            lblError.Text = ex.ToString()
        Finally
            SqlCon.Close()
            SqlCmd.Dispose()
            SqlCon.Dispose()
        End Try
    End Sub

No comments:

Post a Comment