Friday, February 24, 2012

Get PDF from SQL

Hi guys. I've seen a lot posted about this on various sites and can't come up with a working solution. I've got a PDF saved as a byte array in a SQL image field. I figured out how to save/load with images, and I'm pretty sure it's saving the PDF corectly, but I can't get it to load at all.

Here's what I've got:

byte[] image = (byte[])Com.ExecuteScalar();

stream.Write (image, 0, image.Length);

Response.ContentType = "application/pdf";

Response.OutputStream.Write(image,0,image.Length);

This returns a blank page with some spaces. Now that I think about it, maybe its not saving right then.. Any insight? It'd be greatly appreciated.

Try this:

byte[] image = (byte[])Com.ExecuteScalar();

Response.ClearContent();

Response.ClearHeaders();

Response.ContentType ="application/pdf";

Response.BinaryWrite(image);

Response.Flush();

Response.Close();

|||Hi, thanks. I still got a blank page though. Should that be working, in other words might it not be saving correctly? Is there any way to check? It saves images fine using the same method. Does anyone know any other methods off hand to display it? Thanks for your time.|||

Try saving your byte[] to disk and opening it in Acrobat to see if you are getting valid PDF data out. That code should work i took it straight out of a page that i use.

Martin

|||Make sure it's a separate page that dumps the PDF. If you are doing something silly like setting a session variable that tells a .ASPX page whether to dump the .PDF file, or display a form, you'll confuse the browser. The browser has a tendancy to remember the content type of a specific URL, if the URL remains the same, it expects the content type to remain the same as well.|||

Looks similar to mine:

Dim cmdAsNew SqlCommand("SELECT MimeType,Filename,Data FROM Attachments WHERE ID=@.ID", conn)

cmd.Parameters.Add(New SqlParameter("@.ID", SqlDbType.Int))

cmd.Parameters("@.ID").Value = Request.QueryString("ID")

' cmd.Parameters("@.ID").Value = 3

Dim drAs SqlDataReader

dr = cmd.ExecuteReader

dr.Read()

Response.Clear()

Response.AddHeader("Content-type", dr("MimeType"))

Response.AddHeader("Content-Disposition","inline; filename=""" & dr("Filename") &"""")

Dim buffer()AsByte = dr("Data")

Dim blenAsInteger =CType(dr("Data"),Byte()).Length

Response.OutputStream.Write(buffer, 0, blen)

Response.End()

No comments:

Post a Comment