如何打开 PDF 然后压缩它,然后在 C# 中创建 Base64 编码的字符串

How can I open a PDF then ZIP it and then create a Base64 encoded string in C#

我的任务是将从文件系统检索到的压缩 PDF 嵌入到 C# 中的 XML 文档中。规范规定:

For instance, retrieve the file ‘INV001.pdf’

Compress it to get a ‘INV001.zip’ file.

2/ Encode each .zip to Base64 format

The goal is to transform the zip file, which is a binary object, into a text file.

The content of the text file will be a text String which we will be able to copy/paste into the .xml file

这是我必须使用代码的地方

string docText = null;
using (FileStream originalFileStream = File.Open(myFilePath, FileMode.Open))
{
    using (FileStream compressedFileStream = File.Create("compressed.gz"))
    {
        using (var compressor = new GZipStream(compressedFileStream, CompressionMode.Compress, true))
        {
            originalFileStream.CopyTo(compressor);
            using (StreamReader sr = new StreamReader(compressor))
            {
                docText = sr.ReadToEnd();
            }
        }
    }
}

该行代码抛出异常

using (StreamReader sr = new StreamReader(compressor))

“流不可读”。 我走在正确的轨道上吗?不需要存储 ZIP,只需将其作为 Base64 文本粘贴到 XML 文件中即可。我发现一些关于 SO 的文章暗示了一些方法,但 none 似乎有效! 非常感谢

这似乎有效:

string docText = null;
byte[] data;
using (FileStream originalFileStream = File.Open(myFilePath, FileMode.Open))
{
    using (FileStream compressedFileStream = File.Create("compressed.gz"))
    {
        using (var compressor = new GZipStream(compressedFileStream, CompressionMode.Compress, true))
        {
            originalFileStream.CopyTo(compressor);
            using (MemoryStream ms = new MemoryStream())
            {
                compressor.BaseStream.Seek(0, SeekOrigin.Begin);
                compressor.BaseStream.Position = 0;
                compressor.BaseStream.CopyTo(ms);
                data = ms.ToArray();
                docText = Convert.ToBase64String(data);
            }
        }
    }
}