C# 字节数组转pdf
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14259121/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
byte array to pdf
提问by blue piranha
I am trying to convert content of a file stored in a sql column to a pdf.
我正在尝试将存储在 sql 列中的文件内容转换为 pdf。
I use the following piece of code:
我使用以下代码:
byte[] bytes;
BinaryFormatter bf = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
bf.Serialize(ms, fileContent);
bytes = ms.ToArray();
System.IO.File.WriteAllBytes("hello.pdf", bytes);
The pdf generated is corrupt in the sense that when I open the pdf in notepad++, I see some junk header (which is same irrespective of the fileContent). The junk header is NUL SOH NUL NUL NUL ....
生成的 pdf 是损坏的,因为当我在记事本 ++ 中打开 pdf 时,我看到一些垃圾标题(无论文件内容如何,都是相同的)。垃圾标头是 NUL SOH NUL NUL NUL ....
采纳答案by Andras Zoltan
You shouldn't be using the BinaryFormatter
for this - that's for serializing .Net types to a binary file so they can be read back again as .Net types.
你不应该BinaryFormatter
为此使用- 那是为了将 .Net 类型序列化为二进制文件,以便它们可以作为 .Net 类型再次读回。
If it's stored in the database, hopefully, as a varbinary
- then all you need to do is get the byte array from that (that will depend on your data access technology - EF and Linq to Sql, for example, will create a mapping that makes it trivial to get a byte array) and then write it to the file as you do in your last line of code.
如果它存储在数据库中,希望作为一个varbinary
- 那么你需要做的就是从中获取字节数组(这将取决于你的数据访问技术 - 例如,EF 和 Linq to Sql 将创建一个映射,使获取字节数组很简单),然后像在最后一行代码中一样将其写入文件。
With any luck - I'm hoping that fileContent
here is the byte array? In which case you can just do
运气好 - 我希望这fileContent
是字节数组?在这种情况下,你可以做
System.IO.File.WriteAllBytes("hello.pdf", fileContent);
回答by CharithJ
Usually this happens if something is wrong with the byte array.
如果字节数组有问题,通常会发生这种情况。
File.WriteAllBytes("filename.PDF", Byte[]);
This creates a new file, writes the specified byte array to the file, and then closes the file. If the target file already exists, it is overwritten.
这将创建一个新文件,将指定的字节数组写入该文件,然后关闭该文件。如果目标文件已经存在,它会被覆盖。
Asynchronous implementation of this is also available.
也可以使用异步实现。
public static System.Threading.Tasks.Task WriteAllBytesAsync
(string path, byte[] bytes, System.Threading.CancellationToken cancellationToken = null);