C# 4.0: Convert pdf to byte[] and vice versa

后端 未结 3 1887
庸人自扰
庸人自扰 2020-12-08 18:39

How do I convert a pdf file to a byte[] and vice versa?

相关标签:
3条回答
  • 2020-12-08 19:19

    Easiest way:

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

    Or something along these lines...

    0 讨论(0)
  • 2020-12-08 19:30
    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 讨论(0)
  • 2020-12-08 19:32
    // 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.
    System.IO.File.WriteAllBytes(pdfFilePath, bytes);
    
    0 讨论(0)
提交回复
热议问题