gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 22:16:31 25 4
gpt4 key购买 nike

我正在尝试将二进制数据转换为其原始格式“.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 文件是二进制文件,而不是文本文件,因此实际上,您在第一个代码示例中用错误的数据填充了它。

尝试

    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.WriteAllBytes 记录在 http://msdn.microsoft.com/en-us/library/system.io.file.writeallbytes.aspx如果您有更多问题。

关于c# - 将二进制数据转换为pdf文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14111442/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com