Sunday, March 11, 2012

.PDF FROM SQL Server

I'm storing .PDF documents has binary data in SQL Server 2000. I have no problem getting the .pdf converted to binary data and stroing them but how would I go about getting the data out of SQL Server, converting the data from binary back to .pdf and then displaying .pdf document? Thanks for the help.

ChrisHi there,
This may not be the best way of doing this but it did work for me

Say you've got your table tblFiles with a column "BinData" where the binary data is stored

Now to retrieve you'll do the following:

Dim sqlConnection As New SqlConnection(LocalConnectionString)
Dim sqlCommand As New SqlCommand
sqlCommand.Connection = sqlConnection
//Select BinData. Here DocID is e.g. the Id of the PDF you seek
sqlCommand.CommandText = "SELECT BinData FROM tblFiles WHERE ID =" & DocID & "'"
sqlCommand.CommandType = CommandType.Text
Dim fileData() As Byte
Dim dr As SqlDataReader
sqlConnection.Open()
dr = sqlCommand.ExecuteReader
If dr.HasRows Then
While dr.Read
fileData = dr.Item("BinData")
End While
End If
sqlConnection.Close()

//sDestination is a path to a temporary folder
If Directory.Exists(sDestination) Then
Directory.CreateDirectory(sDestination)
End If
Dim fs As New FileStream(sDestination, FileMode.Create, FileAccess.Write)
Dim bw As New BinaryWriter(fs, System.Text.Encoding.UTF8)
bw.Write(fileData)
bw.Close()
fs.Close()

No comments:

Post a Comment