【问题标题】:How to compress any document received as a stream content in .net core web api?如何压缩.net core web api中作为流内容接收的任何文档?
【发布时间】:2023-02-19 15:35:33
【问题描述】:

我有一个 25MB 的 pdf 文档作为 FileStrem 的请求参数收到,我想压缩或减小它的大小。我怎样才能在 .net 6 中实现这一点?

我尝试使用 GzipStream 对其进行压缩,但它不起作用。

【问题讨论】:

  • 你能分享你的Gzip功能吗?
  • @foadabdollahi // 使用 DeflateStream 使用 var compressStream = new MemoryStream();使用 var compressor = new DeflateStream(compressStream, CompressionMode.Compress); file.CopyTo(压缩器);压缩机。关闭(); var c = compressStream.ToArray(); // 使用 GZipStream Stream 流;使用 (FileStream destinationFile = File.Create("test.pdf")) 使用 (GZipStream output = new(destinationFile, CompressionMode.Compress)) { files.FileStream.CopyTo(output); stream = output.BaseStream; }

标签: c# .net asp.net-core asp.net-web-api asp.net-core-webapi


【解决方案1】:

GzipStream 仅用于压缩和解压缩 GZIP 格式的文件。

如果你想压缩你的 pdf 文档,你可以使用 PdfSharp 和 DotnetZip 包,它们是免费和开源的。

例子:

public static void CompressPdf(string inputFilePath, string outputFilePath)
{
    // Load the input PDF document
    using (var inputStream = File.OpenRead(inputFilePath))
    {
        var pdfDocument = PdfReader.Open(inputStream, PdfDocumentOpenMode.Import);

        // Create a new, empty output PDF document
        var outputDocument = new PdfDocument();

        // Compress each page of the input document and add it to the output document
        foreach (var page in pdfDocument.Pages)
        {
            using (var stream = new MemoryStream())
            {
                // Save the page to a stream
                page.Save(stream, false);

                // Compress the stream using DotNetZip
                stream.Position = 0;
                var compressedStream = new MemoryStream();
                using (var zip = new ZipFile())
                {
                    zip.AddEntry("Page" + page.PageNumber.ToString(), stream);
                    zip.Save(compressedStream);
                }

                // Create a new PDF page from the compressed stream and add it to the output document
                compressedStream.Position = 0;
                var compressedPage = PdfReader.Open(compressedStream, PdfDocumentOpenMode.Import).Pages[0];
                outputDocument.AddPage(compressedPage);
            }
        }

        // Save the compressed PDF document to the output file
        using (var outputStream = File.Create(outputFilePath))
        {
            outputDocument.Save(outputStream);
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-01
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多