How to Save and Display a PDf/Word file ?

For displaying, it will save the pdf/word to temp folder then open it and after closing will delete the temp file.


Private Sub ShowPDF_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ShowPDF.Click

Dim sFilePath As String

Dim buffer As Byte()

Using con As New SqlConnection()

con.ConnectionString = ConfigurationManager.ConnectionStrings()("SqlServerConnection").ConnectionString

con.Open()

Using cmd As New SqlCommand("SELECT PDF_file FROM PDF_table WHERE ID = @ID", con)

Dim ID As New SqlParameter("@ID", SqlDbType.Int)

ID.Value = TextBoxParentID.Text

cmd.Parameters.Add(ID)

buffer = cmd.ExecuteScalar()

End Using

con.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 OpenFile)

act.BeginInvoke(sFilePath, Nothing, Nothing)

End Sub

Private Shared Sub OpenFile(ByVal sFilePath As String)

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

Advertisements

About Ahmed

Software craftsman, programmer, developer, system/business analyst, DBA and PM.
This entry was posted in Databases, Programming, SQL-Server, VB.NET and tagged , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s