Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

byte array to pdf

I am trying to convert content of a file stored in a sql column to a pdf.

I use the following piece of code:

byte[] bytes; BinaryFormatter bf = new BinaryFormatter(); MemoryStream ms = new MemoryStream(); bf.Serialize(ms, fileContent); bytes = ms.ToArray(); System.IO.File.WriteAllBytes("hello.pdf", bytes); 

The pdf generated is corrupt in the sense that when I open the pdf in notepad++, I see some junk header (which is same irrespective of the fileContent). The junk header is NUL SOH NUL NUL NUL ....

like image 263
blue piranha Avatar asked Jan 10 '13 13:01

blue piranha


People also ask

How to download PDF file from byte array in c#?

GetBytes(fileBytes); // Here the fileBytes are already encoded (Encrypt) value. Just convert from string to byte Response. Clear(); MemoryStream ms = new MemoryStream(pdfasBytes); Response. ContentType = "application/pdf"; Response.

How can I tell if a byte array is PDF?

Check the first 4 bytes of the array. If those are 0x25 0x50 0x44 0x46 then it's most probably a PDF file.

How do you convert data to PDF?

Click the Select a file button above or drag and drop a file into the drop zone. Select the document you want to convert to PDF. Watch Adobe Acrobat do its PDF conversion magic. Download your new PDF or sign in to share it.


1 Answers

You shouldn't be using the BinaryFormatter for this - that's for serializing .Net types to a binary file so they can be read back again as .Net types.

If it's stored in the database, hopefully, as a varbinary - then all you need to do is get the byte array from that (that will depend on your data access technology - EF and Linq to Sql, for example, will create a mapping that makes it trivial to get a byte array) and then write it to the file as you do in your last line of code.

With any luck - I'm hoping that fileContent here is the byte array? In which case you can just do

System.IO.File.WriteAllBytes("hello.pdf", fileContent); 
like image 70
Andras Zoltan Avatar answered Oct 02 '22 18:10

Andras Zoltan