Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8030767
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 5, 20262026-06-05T00:52:38+00:00 2026-06-05T00:52:38+00:00

I have a view that returns a pdf (using iTextSharp) with multiple pages, but

  • 0

I have a view that returns a pdf (using iTextSharp) with multiple pages, but now I have to change it so that each page is a separate pdf (with it’s own unique title) and return a zip file.

My original code looks like this:

public FileStreamResult DownloadPDF()
{
    MemoryStream workStream = new MemoryStream();
    Document document = new Document();
    PdfWriter.GetInstance(document, workStream).CloseStream = false;
    document.Open();

    // Populate pdf items

    document.Close();

    byte[] byteInfo = workStream.ToArray();
    workStream.Write(byteInfo, 0, byteInfo.Length);
    workStream.Position = 0;

    FileStreamResult fileResult = new FileStreamResult(workStream, "application/pdf");
    fileResult.FileDownloadName = "fileName";

    return fileResult;
}

It looks pretty simple to compress a file with gzip, but I don’t know how to gzip multiple files and return it as one zip file. Or should I use something other than gzip, like dotnetzip or sharpzip?

Thanks in advance!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-05T00:52:40+00:00Added an answer on June 5, 2026 at 12:52 am

    If your solution works then the easiest thing to do is to just keep it, as is.

    On the other hand I do have some comments about your usage of the DoTNetZip library.

    First, your code is sort of misguided. In this section:

    byte[] byteInfo = workStream.ToArray();                        
    
    zip.Save(workStream);                        
    
    workStream.Write(byteInfo, 0, byteInfo.Length);                        
    workStream.Position = 0;                        
    

    …you are reading the workStream into an array. But at that point, you haven’t written anything to workStream, so the array is empty, zero-length. Then you save the zip into the workstream. Then you write the array (of zero length) into the same workstream. This is a NO-OP. Finally you reset the position.

    You could replace all of that with :

    zip.Save(workStream);                        
    workStream.Position = 0;                        
    

    This isn’t an issue with DotNetZip per se, it’s just an mis-understanding on your part regarding the operation of streams.

    OK, Next, you are allocating temporary buffers (memorystreams) unnecessarily. Think of a MemoryStream as just an array of bytes, with a Stream wrapper on it, to support Write(), Read(), Seek(), and so on. Essentially your code is writing data into that temporary buffer, then telling DotNetZip to read the data from the temp buffer into its own buffer for compression. You don’t need that interim buffer. It works the way you’ve done it, but it could be more efficient.

    DotNetZip has an AddEntry() overload that accepts a writer delegate. The delegate is a function that DotNetZip calls to tell your app to write the entry content into the zip archive. Your code writes uncompressed bytes, and DotNetZip compresses and writes them to the output stream.

    In that writer delegate, your code writes directly into the DotNetZip stream – the stream that is passed into the delegate by DotNetZip. There’s no intervening buffer. Nice for efficiency.

    Keep in mind the rules about closures. If you call this writer delegate in a for loop, you need to have a way of retrieving the “bla” corresponding to the zipentry within the delegate. The delegate does not get executed until zip.Save() is called! So you cannot rely on the value of ‘bla’ from the loop.

    public FileStreamResult DownloadPDF() 
    { 
        MemoryStream workStream = new MemoryStream(); 
        using(var zip = new ZipFile()) 
        {
            foreach(Bla bla in Blas) 
            { 
                zip.AddEntry(bla.filename + ".pdf", (name,stream) => {
                        var thisBla = GetBlaFromName(name);
                        Document document = new Document(); 
                        PdfWriter.GetInstance(document, stream).CloseStream = false; 
    
                        document.Open(); 
    
                        // write PDF Content for thisBla into stream/PdfWriter 
    
                        document.Close(); 
                    });
            } 
    
            zip.Save(workStream); 
        }
        workStream.Position = 0; 
    
        FileStreamResult fileResult = new FileStreamResult(workStream, System.Net.Mime.MediaTypeNames.Application.Zip); 
        fileResult.FileDownloadName = "MultiplePDFs.zip"; 
    
        return fileResult; 
    }
    

    Finally, I don’t particularly like your creation of a FileStreamResult from a MemoryStream. The problem is your entire zip file is kept in memory, which can be very hard on memory usage. If your zip files are large, your code will retain all of the content in memory.

    I don’t know enough about the MVC3 model to know if there is something in it that helps with this. If there is not, you can use an Anonymous Pipe to invert the direction of the streams, and eliminate the need to hold all the compressed data in memory.

    Here’s what I mean: creating a FileStreamResult requires that you provide a readable stream. If you use a MemoryStream, in order to make it readable, you need to write to it first, then seek back to position 0, before passing it to the FileStreamResult constructor. This means all the content for that zip file has to be held in memory contiguously at some point in time.

    Suppose you could provide a readable stream to the FileStreamResult constructor, that would allow the reader to read at exactly the moment you wrote to it. This is what an anonymous pipe stream does. It allows your code to use a writeable stream, while the MVC code gets its readable stream.

    Here’s what it would look like in code.

    static Stream GetPipedStream(Action<Stream> writeAction) 
    { 
        AnonymousPipeServerStream pipeServer = new AnonymousPipeServerStream(); 
        ThreadPool.QueueUserWorkItem(s => 
        { 
            using (pipeServer) 
            { 
                writeAction(pipeServer); 
                pipeServer.WaitForPipeDrain(); 
            } 
        }); 
        return new AnonymousPipeClientStream(pipeServer.GetClientHandleAsString()); 
    } 
    
    
    public FileStreamResult DownloadPDF() 
    {
        var readable = 
            GetPipedStream(output => { 
    
                using(var zip = new ZipFile()) 
                {
                    foreach(Bla bla in Blas) 
                    { 
                        zip.AddEntry(bla.filename + ".pdf", (name,stream) => {
                            var thisBla = GetBlaFromName(name);
                            Document document = new Document(); 
                            PdfWriter.GetInstance(document, stream).CloseStream = false; 
    
                            document.Open(); 
    
                            // write PDF Content for thisBla to PdfWriter
    
                            document.Close(); 
                        });
                    } 
    
                    zip.Save(output); 
                }
            }); 
    
        var fileResult = new FileStreamResult(readable, System.Net.Mime.MediaTypeNames.Application.Zip); 
        fileResult.FileDownloadName = "MultiplePDFs.zip"; 
    
        return fileResult; 
    }
    

    I haven’t tried this but it ought to work. This has an advantage over what you wrote, of being more memory efficient. The disadvantage is that it is quite a bit more complex, using named pipes and several anonymous functions.

    This makes sense only if the zip content is into the >1MB range. If your zips are smaller than that, then you can just do it the first way I’ve shown, above.


    Addendum

    Why can you not rely on the value of bla within the anonymous method?

    There are two key points. First, the foreach loop defines a
    variable named bla, which takes a different value, each time
    through the loop. Seems obvious but it’s worth stating it
    explicitly.

    Second, the anonymous method is being passed as an argument to
    the ZipFile.AddEntry() method, and it won’t run at the time the
    foreach loop runs. In fact the anonymous method gets called
    repeatedly, once for each entry added, at the time of
    ZipFile.Save(). If you refer to bla within the anonymous
    method, it gets the last value assigned to bla, because that
    is the value bla holds at the time ZipFile.Save() runs.

    It’s the deferred execution that causes the difficulty.

    What you want is each distinct value of bla from the foreach loop to be
    accessible at the time the anonymous function is invoked – later, outside the foreach loop. You
    could do this with a utility method (GetBlaForName()), like I showed above. You can
    also do this with an additional closure, like so:

    Action<String,Stream> GetEntryWriter(Bla bla)
    {
       return new Action<String,Stream>((name,stream) => {
         Document document = new Document();  
         PdfWriter.GetInstance(document, stream).CloseStream = false;  
    
         document.Open();  
    
         // write PDF Content for bla to PdfWriter 
    
         document.Close();  
      };
    }
    
    foreach(var bla in Blas)
    {
      zip.AddEntry(bla.filename + ".pdf", GetEntryWriter(bla));
    }
    

    The GetEntryWriter returns a method – actually an Action, which is just a typed method. Each time through the loop, a new instance of that Action is created, and it references a different value for bla. That Action is not called until the time of ZipFile.Save().

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a simple Django view that just returns URL parameters, but if I
I have a method that returns a PDF file using DOMPDF . It sends
I have a view that returns 2 ints from a table using a CTE.
I have a function that returns a generated PDF file but the problem is
I have a django view that returns HTTP 301 on a curl request: grapefruit:~
Im having a very strange problem, i have a complicated view that returns incorrect
If i have a controller action Create that returns a view with the following
I have a sub form that looks like a datasheet view. It returns prices
I have a view that returns data like the following: 1 | Abita |
I have a MVC View that generates multiple Ajax.BeginForm , with a button in

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.