hey everyone, i am to create a database filled with pdf files and its stored into binary. i was able to convert each file into binary but the problem is dat now i cant display it in the viewer.. can someone help me?
i remember that i used to do it on a pic through:

picStudImg.Image = Image.FromStream(New MemoryStream(CType(ds.Tables("studinfo_t").Rows(inc).Item("Image"), Byte())))

tnx for helping guys..

Dani AI

Generated

If your PDFs are stored as varbinary in SQL Server, do not try to treat them like images (e.g., Image.FromStream). Browsers render PDFs when you stream the bytes with the correct headers. showed how to round-trip a file to disk in a desktop app; for ASP.NET you want to stream directly to the response so the built-in browser PDF viewer opens it inline.

Here is a minimal VB.NET HttpHandler (.ashx) that streams a PDF by id:

Imports System.Data.SqlClient
Public Class Pdf : Implements IHttpHandler
  Public Sub ProcessRequest(ctx As HttpContext) Implements IHttpHandler.ProcessRequest
    Dim id = Integer.Parse(ctx.Request("id"))
    Dim bytes = LoadPdf(id)
    ctx.Response.Clear()
    ctx.Response.ContentType = "application/pdf"
    ctx.Response.AddHeader("Content-Disposition", "inline; filename=document.pdf")
    ctx.Response.AddHeader("Content-Length", bytes.Length.ToString())
    ctx.Response.BinaryWrite(bytes)
    ctx.Response.Flush()
    ctx.Response.End()
  End Sub
  Public ReadOnly Property IsReusable As Boolean Implements IHttpHandler.IsReusable
    Get : Return False : End Get
  End Property
  Private Function LoadPdf(id As Integer) As Byte()
    Using cn As New SqlConnection("your-connection-string"),
          cmd As New SqlCommand("SELECT PDF FROM dbo.PDF WHERE RecordId=@id", cn)
      cmd.Parameters.Add("@id", SqlDbType.Int).Value = id
      cn.Open()
      Return CType(cmd.ExecuteScalar(), Byte())
    End Using
  End Function
End Class

Troubleshooting tips:

  • Verify the column really contains a valid PDF (try writing the bytes to disk and opening them).
  • Ensure nothing is written to the response before the headers (no server controls writing HTML on the same request).
  • Use inline to display in-browser, attachment to force download. Modern browsers handle PDFs natively; no extra viewer control is required.
  • For large files, stream in chunks with SqlDataReader and CommandBehavior.SequentialAccess to avoid loading the whole blob into memory.
  • If the PDFs are not sensitive, enable caching; if they are, turn caching off and send Cache-Control: no-store.

Recommended Answers

All 3 Replies

This code will let you read and write from a binary file.

Imports System.IO

Module Module1

    Sub Main()
        Dim Stream As FileStream
        Try
            Stream = New FileStream("test.dat", FileMode.Create)
        Catch E As Exception
            Console.WriteLine("Error creating test.Dat")
            Console.WriteLine("Error {0}", E.Message)
        End Try

        Dim BinaryStream As New BinaryWriter(Stream)

        Dim Age As Integer = 21
        Dim Salary As Double = 100000.0
        Dim Name As String = "Joe"

        Try
            BinaryStream.Write(Age)
            BinaryStream.Write(Salary)
            BinaryStream.Write(Name)
            BinaryStream.Close()

            Console.WriteLine("Data written to test.Dat")
        Catch E As Exception
            Console.WriteLine("Error writing to test.Dat")
            Console.WriteLine("Error {0}", E.Message)
        End Try
        
        'Read 
        
        Try
            Stream = New FileStream("test.dat", FileMode.Open)
        Catch E As Exception
            Console.WriteLine("Error opening test.Dat")
            Console.WriteLine("Error {0}", E.Message)
        End Try

        Dim BinaryStreamReader As New BinaryReader(Stream)

        Try
            Age = BinaryStreamReader.ReadInt32()
            Salary = BinaryStreamReader.ReadDouble()
            Name = BinaryStreamReader.ReadString()
            BinaryStreamReader.Close()

            Console.WriteLine("Age: {0}", Age)
            Console.WriteLine("Salary: {0}", Salary)
            Console.WriteLine("Name: {0}", Name)
        Catch E As Exception
            Console.WriteLine("Error reading to test.Dat")
            Console.WriteLine("Error {0}", E.Message)
        End Try

    End Sub

End Module

Here is another approach.

Imports System.Data.SqlClient

'IF OBJECT_ID('PDF', 'U') IS NOT NULL DROP TABLE PDF
'CREATE TABLE PDF
'(
'  RecordId int identity(1000, 1) PRIMARY KEY,
'  PDF varbinary(max)
')

Public Class frmPDF

  Private Sub ButtonUpload_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonUpload.Click
    Using conn As New SqlConnection("Data Source=apex2006sql;Initial Catalog=Scott;Integrated Security=True;")
      conn.Open()
      Using cmd As New SqlCommand("Insert Into PDF (PDF) Values (@PDF)", conn)
        cmd.Parameters.Add(New SqlParameter("@PDF", SqlDbType.VarBinary)).Value = System.IO.File.ReadAllBytes("C:\file.pdf")
        cmd.ExecuteNonQuery()
      End Using
      conn.Close()
    End Using
  End Sub

  Private Sub ButtonDownload_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonDownload.Click
    Dim sFilePath As String
    Dim buffer As Byte()
    Using conn As New SqlConnection("Data Source=apex2006sql;Initial Catalog=Scott;Integrated Security=True;")
      conn.Open()
      Using cmd As New SqlCommand("Select Top 1 PDF From PDF", conn)
        buffer = cmd.ExecuteScalar()
      End Using
      conn.Close()
    End Using
    sFilePath = System.IO.Path.GetTempFileName()
    System.IO.File.Move(sFilePath, System.IO.Path.ChangeExtension(sFilePath, ".pdf"))
    sFilePath = System.IO.Path.ChangeExtension(sFilePath, ".pdf")
    System.IO.File.WriteAllBytes(sFilePath, buffer)
    Dim act As Action(Of String) = New Action(Of String)(AddressOf OpenPDFFile)
    act.BeginInvoke(sFilePath, Nothing, Nothing)
  End Sub

  Private Shared Sub OpenPDFFile(ByVal sFilePath)
    Using p As New System.Diagnostics.Process
      p.StartInfo = New System.Diagnostics.ProcessStartInfo(sFilePath)
      p.Start()
      p.WaitForExit()
      Try
        System.IO.File.Delete(sFilePath)
      Catch
      End Try
    End Using
  End Sub
End Class

The OpenPDF method is launched in another thread so it can wait for the process to terminate then clean up the temporary PDF file written to disk.

Very Hepful Thanks :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.