字节数组到pdf

blu*_*nha 30 c# file writeallbytes

我正在尝试将存储在sql列中的文件的内容转换为pdf.

我使用以下代码:

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

生成的pdf在某种意义上是腐败的,当我在notepad ++中打开pdf时,我看到一些垃圾标题(无论fileContent如何都是相同的).垃圾标题是NUL SOH NUL NUL NUL ....

And*_*tan 58

您不应该使用BinaryFormatterfor - 这是为了将.Net类型序列化为二进制文件,以便它们可以作为.Net类型再次读回.

如果它存储在数据库中,希望作为varbinary- 那么您需要做的就是从中获取字节数组(这将取决于您的数据访问技术 - 例如,EF和Linq到Sql将创建一个映射,使得到一个字节数组很简单,然后像在最后一行代码中那样将它写入文件.

运气好的话 - 我希望这fileContent是字节数组吗?在这种情况下你可以做到

System.IO.File.WriteAllBytes("hello.pdf", fileContent);
Run Code Online (Sandbox Code Playgroud)