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

问题描述 投票:0回答:4

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

c# pdf arrays
4个回答
163
投票
// 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);

0
投票

PDF 可以直接以字节为单位读取 byte[] 字节 = System.IO.File.ReadAllBytes(PdfFilePath);

此外,要将 PDF 文档加载到内存中:https://sautinsoft.com/products/document/help/net/developer-guide/load-pdf-document-net-csharp-vb.php

要在内存使用中将 PDF 转换为 Word:https://sautinsoft.com/products/pdf-focus/help/net/developer-guide/convert-pdf-to-word-in-memory-csharp-vb-net .php


-1
投票
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;
}

-4
投票

最简单的方法:

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

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

© www.soinside.com 2019 - 2024. All rights reserved.