将二进制数据转换为pdf文件

本文关键字:pdf 文件 转换 二进制 数据 | 更新日期: 2023-09-27 17:50:31

我正在尝试将二进制数据转换为其原始格式". 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);
}

将二进制数据转换为pdf文件

将文件作为文本写入,但应该写入原始字节。pdf文件是二进制文件,而不是文本文件,因此实际上,您在第一个代码示例中填充了错误的数据。

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

System.IO.File。如果您有更多问题,请访问http://msdn.microsoft.com/en-us/library/system.io.file.writeallbytes.aspx查看WriteAllBytes。

尝试文件。使用原始数据(binaryData) WriteAllBytes,不要尝试将其转换为其他任何内容

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