首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C# 4.0:将pdf格式转换为byte[]格式,反之亦然

C# 4.0:将pdf格式转换为byte[]格式,反之亦然
EN

Stack Overflow用户
提问于 2010-03-16 11:04:36
回答 3查看 146.6K关注 0票数 69

如何将pdf文件转换为byte[]格式,反之亦然?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2010-03-16 11:07:43

代码语言:javascript
复制
// loading bytes from a file is very easy in C#. The built in System.IO.File.ReadAll* methods take care of making sure every byte is read properly.
// note that for Linux, you will not need the c: part
// just swap out the example folder here with your actual full file path
string pdfFilePath = "c:/pdfdocuments/myfile.pdf";
byte[] bytes = System.IO.File.ReadAllBytes(pdfFilePath);

// munge bytes with whatever pdf software you want, i.e. http://sourceforge.net/projects/itextsharp/
// bytes = MungePdfBytes(bytes); // MungePdfBytes is your custom method to change the PDF data
// ...
// make sure to cleanup after yourself

// and save back - System.IO.File.WriteAll* makes sure all bytes are written properly - this will overwrite the file, if you don't want that, change the path here to something else
System.IO.File.WriteAllBytes(pdfFilePath, bytes);
票数 149
EN

Stack Overflow用户

发布于 2020-05-13 02:21:28

代码语言:javascript
复制
using (FileStream fs = new FileStream("sample.pdf", FileMode.Open, FileAccess.Read))
            {
                byte[] bytes = new byte[fs.Length];
                int numBytesToRead = (int)fs.Length;
                int numBytesRead = 0;
                while (numBytesToRead > 0)
                {
                    // Read may return anything from 0 to numBytesToRead.
                    int n = fs.Read(bytes, numBytesRead, numBytesToRead);

                    // Break when the end of the file is reached.
                    if (n == 0)
                    {
                        break;
                    }

                    numBytesRead += n;
                    numBytesToRead -= n;
                }
                numBytesToRead = bytes.Length;
}
票数 0
EN

Stack Overflow用户

发布于 2010-03-16 11:11:01

最简单的方法:

代码语言:javascript
复制
byte[] buffer;
using (Stream stream = new IO.FileStream("file.pdf"))
{
   buffer = new byte[stream.Length - 1];
   stream.Read(buffer, 0, buffer.Length);
}

using (Stream stream = new IO.FileStream("newFile.pdf"))
{
   stream.Write(buffer, 0, buffer.Length);
}

或者其他类似的东西...

票数 -4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2451864

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档