2013-01-01 58 views
4

我試圖將二進制數據轉換爲其原始格式「.PDF」,但是其中任何一種解決方案都有助於我的hed。第一個是一個小的,它創建一個PDF文件,但它看起來是空的。第二個也創建一個PDF文件,但我無法打開它。錯誤在哪裏?將二進制數據轉換爲pdf文件

首先代碼:

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); 

二碼:

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); 
} 
+0

如果你願意,你可以看看[this](http://stackoverflow.com/questions/3961804/itextsharp-creation-of-a-pdf-from-a-list-of-byte-arrays)想從字節數組中創建PDF。 – Tilak

回答

6

你正在將文件寫入文本,但您應該寫入原始字節。 .PDF文件是一個二進制文件,而不是文本文件,因此實際上,您在第一個代碼示例中填寫了錯誤的數據。

嘗試

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在http://msdn.microsoft.com/en-us/library/system.io.file.writeallbytes.aspx被記錄在案,如果您有更多的問題。

+0

這是我在多個問題和搜索中找到的最佳答案。我只想建議參數化這個命令文本,而不是連接一個字符串。即使你的id變量被設置爲int,並且你不關心安全性,但爲了一致性,它仍然是一個好習慣。 – Brad

3

與原始數據嘗試File.WriteAllBytes(binaryData)不要試圖將其轉換爲別的

0
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();