Convert binary data to pdf file

I am trying to convert binary data to the original ".PDF" format, but any of the solutions that I have are. The first is small, it creates a PDF file, but it seems empty. The second also creates a PDF file, but I cannot open it. Where is the mistake?

First code:

Conn.Open(); SqlCommand cmd = Conn.CreateCommand(); cmd.CommandText = "Select Artigo From Artigo WHERE (IDArtigo ='" + id + "')"; byte[] binaryData = (byte[])cmd.ExecuteScalar(); string s = Encoding.UTF8.GetString(binaryData); File.WriteAllText("algo.pdf", s); 

Second code:

 Conn.Open(); SqlCommand cmd = Conn.CreateCommand(); cmd.CommandText = "Select Artigo From Artigo WHERE (IDArtigo ='" + id + "')"; byte[] binaryData = (byte[])cmd.ExecuteScalar(); // Convert the binary input into Base64 UUEncoded output. string base64String; try { base64String = System.Convert.ToBase64String(binaryData, 0, binaryData.Length); } catch (System.ArgumentNullException) { MessageBox.Show("Binary data array is null."); return; } cmd.CommandText = "Select Titulo From Artigo WHERE (IDArtigo ='" + id + "')"; string titulo = (string)cmd.ExecuteScalar(); // Write the UUEncoded version to the output file. System.IO.StreamWriter outFile; try { outFile = new StreamWriter(titulo + ".pdf", false, System.Text.Encoding.ASCII); outFile.Write(base64String); outFile.Close(); } catch (System.Exception exp) { System.Console.WriteLine("{0}", exp.Message); } 
+4
source share
3 answers

You write the file as text, but you must write raw bytes. The .PDF file is a binary file, not a text file, so in reality you are filling it with invalid data in your first code sample.

Try

  Conn.Open(); SqlCommand cmd = Conn.CreateCommand(); cmd.CommandText = "Select Artigo From Artigo WHERE (IDArtigo ='" + id + "')"; byte[] binaryData = (byte[])cmd.ExecuteScalar(); File.WriteAllBytes(("algo.pdf", binaryData); string s = Encoding.UTF8.GetString(binaryData); 

System.IO.File.WriteAllBytes is documented at http://msdn.microsoft.com/en-us/library/system.io.file.writeallbytes.aspx if you have further questions.

+7
source

Try File.WriteAllBytes with raw data (binaryData) and don't try to convert it to anything else

+3
source
 string sql = "select Lsn_File from Lessons_tbl where Lsn_name = '"TextBox1.Text + "'"; cmd = new SqlCommand(sql, dal.cn()); dal.Open(); SqlDataReader dr = cmd.ExecuteReader(); dr.Read(); if (dr.HasRows) { byte[] lesson = (byte[])(dr[0]); spathfile = System.IO.Path.GetTempFileName(); //move from soures to destination the extension until now is .temp System.IO.File.Move(spathfile, System.IO.Path.ChangeExtension(spathfile,".pdf")); //make it real pdf file extension .pdf spathfile = System.IO.Path.ChangeExtension(spathfile, ".pdf"); System.IO.File.WriteAllBytes(spathfile, lesson ); this.axAcroPDF1.LoadFile(spathfile); dal.close(); 
0
source

All Articles