Creating Zip Files from Memory Stream C#

前端 未结 5 2133
执笔经年
执笔经年 2021-02-04 06:51

Basically the user should be able to click on one link and download multiple pdf files. But the Catch is I cannot create files on server or anywhere. Everything has to be in mem

5条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-04 07:45

    This link describes how to create a zip from a MemoryStream using SharpZipLib: https://github.com/icsharpcode/SharpZipLib/wiki/Zip-Samples#wiki-anchorMemory. Using this and iTextSharp, I was able to zip multiple PDF files that were created in memory.

    Here is my code:

    MemoryStream outputMemStream = new MemoryStream();
    ZipOutputStream zipStream = new ZipOutputStream(outputMemStream);
    
    zipStream.SetLevel(3); //0-9, 9 being the highest level of compression
    byte[] bytes = null;
    
    // loops through the PDFs I need to create
    foreach (var record in records)
    {
        var newEntry = new ZipEntry("test" + i + ".pdf");
        newEntry.DateTime = DateTime.Now;
    
        zipStream.PutNextEntry(newEntry);
    
        bytes = CreatePDF(++i);
    
        MemoryStream inStream = new MemoryStream(bytes);
        StreamUtils.Copy(inStream, zipStream, new byte[4096]);
        inStream.Close();
        zipStream.CloseEntry();
    }
    
    zipStream.IsStreamOwner = false;    // False stops the Close also Closing the underlying stream.
    zipStream.Close();          // Must finish the ZipOutputStream before using outputMemStream.
    
    outputMemStream.Position = 0;
    
    return File(outputMemStream.ToArray(), "application/octet-stream", "reports.zip");
    

    The CreatePDF Method:

    private static byte[] CreatePDF(int i)
    {
        byte[] bytes = null;
        using (MemoryStream ms = new MemoryStream())
        {
            Document document = new Document(PageSize.A4, 25, 25, 30, 30);
            PdfWriter writer = PdfWriter.GetInstance(document, ms);
            document.Open();
            document.Add(new Paragraph("Hello World " + i));
            document.Close();
            writer.Close();
            bytes = ms.ToArray();
        }
    
        return bytes;
    }
    

提交回复
热议问题