Download multiple PDF Report as Zip using ZipAchive in ASP.Net MVC

bigbear
 
on Nov 05, 2019 11:32 PM
Sample_152904.zip
911 Views

So I currently have all my PDF records being put in a zip file.

Each record that is selected is put into a single zip.

When I create a Zip and I have multiple records in it each record is the same. Even when I pick different records and the byte[]s are different.

it either picks the very last one or the first one and each file name is of the correct record but the data inside the file each one is the exact same.

Controller

public class HomeController : Controller
{
    // GET: /Home/Export
    public ActionResult Index()
    {
        return View();
    }
 
    [HttpPost]
    public ActionResult Export(string[] quoteIDs)
    {
        List<byte[]> bytesArray = new List<byte[]>();
        List<string> fileNameArray = new List<string>();
        NorthwindEntities entities = new NorthwindEntities();
        if (quoteIDs != null)
        {
            string reportType = "PDF";
            string mimeType = "", encoding = "", fileNameExtension = "";
            foreach (var qid in quoteIDs)
            {
                List<Customer> lstCustomers = new List<Customer>();
                var quote = entities.Customers.Where(x => x.CustomerID == qid).FirstOrDefault();
                lstCustomers.Add(quote);
 
                LocalReport localReport = new LocalReport()
                {
                    ReportPath = Server.MapPath("~/CustomerReport.rdlc")
                };
                ReportDataSource rds = new ReportDataSource("Customers", lstCustomers);
                localReport.DataSources.Add(rds);
 
                string deviceInfo =
                                "<DeviceInfo>" +
                                "   <OutputFormat>" + reportType + "</OutputFormat>" +
                                "   <PageWidth>8.5in</PageWidth>" +
                                "   <PageHeight>11in</PageHeight>" +
                                "   <MarginTop>0.5in</MarginTop>" +
                                "   <MarginLeft>0in</MarginLeft>" +
                                "   <MarginRight>0in</MarginRight>" +
                                "   <MarginBottom>0in</MarginBottom>" +
                                "</DeviceInfo>";
 
                Warning[] warnings;
                string[] streams;
                byte[] renderedBytes = localReport.Render(reportType, deviceInfo, out mimeType, out encoding,
                                                            out fileNameExtension, out streams, out warnings);
                bytesArray.Add(renderedBytes);
                fileNameArray.Add(qid + "." + fileNameExtension);
            }
            TempData["Data"] = bytesArray;
            TempData["File"] = fileNameArray;
            return new JsonResult() { Data = new { MimeType = mimeType } };
        }
 
        return RedirectToAction("VirtualService");
    }
 
    [HttpGet]
    public virtual ActionResult DownloadReportZip(string mimeType)
    {
           byte[] bytearray = null;
 
           if(TempData["Data"] != null)
           {
               List<byte[]> lstBytesArray = TempData["Data"] as List<byte[]>;
               List<string> lstNamesArray = TempData["File"] as List<string>;
 
               using(MemoryStream ms = new MemoryStream())
               {
                   // Creates the .zip
                   using(ZipArchive archive = new ZipArchive(ms, ZipArchiveMode.Create))
                   {
                       int i = 0;
                       foreach(byte[] bytes in lstBytesArray)  // iterate through each file
                       {
                           // Creates empty file and names it inside of .zip
                           ZipArchiveEntry zipItem = archive.CreateEntry(lstNamesArray[i] + ".pdf");
                           // adds file to zipItem
                           using (MemoryStream ms4file = new MemoryStream(bytes))
                           {
                               using(Stream stream = zipItem.Open())
                               {
                                   ms4file.CopyTo(stream);
                               }
                           }
                       }
                   }
                bytearray = ms.ToArray();
            }               
        }
        else
        {
            return new EmptyResult();
        }
           
        return File(bytearray, "application/zip");
    }
}

 

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Nov 07, 2019 04:16 AM
on Nov 11, 2019 11:20 AM

Refer the below sample code.

Namespaces

using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.Reporting.WebForms;
using System.Web.Mvc;
using System.IO.Compression;

Controller

public class HomeController : Controller
{
    //
    // GET: /Home/
    public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Export(string[] quoteIDs)
    {
        List<SourceFile> files = new List<SourceFile>();
        NorthwindEntities entities = new NorthwindEntities();
        if (quoteIDs != null)
        {
            string reportType = "PDF";
            string mimeType = "", encoding = "", fileNameExtension = "";
            foreach (var qid in quoteIDs)
            {
                List<Customer> lstCustomers = new List<Customer>();
                var quote = entities.Customers.Where(x => x.CustomerID == qid).FirstOrDefault();
                lstCustomers.Add(quote);

                LocalReport localReport = new LocalReport()
                {
                    ReportPath = Server.MapPath("~/CustomerReport.rdlc")
                };
                ReportDataSource rds = new ReportDataSource("CustomerDataSet", lstCustomers);
                localReport.DataSources.Add(rds);

                string deviceInfo =
                                "<DeviceInfo>" +
                                "   <OutputFormat>" + reportType + "</OutputFormat>" +
                                "   <PageWidth>8.5in</PageWidth>" +
                                "   <PageHeight>11in</PageHeight>" +
                                "   <MarginTop>0.5in</MarginTop>" +
                                "   <MarginLeft>0in</MarginLeft>" +
                                "   <MarginRight>0in</MarginRight>" +
                                "   <MarginBottom>0in</MarginBottom>" +
                                "</DeviceInfo>";

                Warning[] warnings;
                string[] streams;
                byte[] renderedBytes = localReport.Render(reportType, deviceInfo, out mimeType, out encoding,
                                                            out fileNameExtension, out streams, out warnings);
                files.Add(new SourceFile { Extension = "." + fileNameExtension, Name = qid, FileBytes = renderedBytes });
            }
            TempData["Files"] = files;
            return new JsonResult() { Data = new { MimeType = mimeType } };
        }

        return RedirectToAction("VirtualService");
    }

    [HttpGet]
    public virtual ActionResult Download()
    {
        if (TempData["Files"] != null)
        {
            List<SourceFile> files = TempData["Files"] as List<SourceFile>;
            byte[] bytearray = null;

            using (MemoryStream ms = new MemoryStream())
            {
                // Creates the .zip
                using (ZipArchive archive = new ZipArchive(ms, ZipArchiveMode.Create, true))
                {
                    foreach (SourceFile file in files)  // iterate through each file
                    {
                        // Creates empty file and names it inside of .zip
                        ZipArchiveEntry zipItem = archive.CreateEntry(file.Name + file.Extension);
                        // adds file to zipItem
                        using (MemoryStream ms4file = new MemoryStream(file.FileBytes))
                        {
                            using (Stream stream = zipItem.Open())
                            {
                                ms4file.CopyTo(stream);
                            }
                        }
                    }
                }
                bytearray = ms.ToArray();
            }

            return File(bytearray, "application/zip");
        }
        else
        {
            return new EmptyResult();
        }
    }

    public class SourceFile
    {
        public string Name { get; set; }
        public string Extension { get; set; }
        public byte[] FileBytes { get; set; }
    }
}

View

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
    $(function () {
        $('#btnGetChecks').on('click', function () {
            var arrSelectedQIDs = [];
            $("input:checked").each(function (index, value) {
                arrSelectedQIDs.push($(value).val());
            });
            $.ajax({
                type: "POST",
                url: "/Home/Export/",
                contentType: "application/json; charset=utf-8",
                data: JSON.stringify({ quoteIDs: arrSelectedQIDs }),
                success: function (data) {
                    window.location = '/Home/Download';
                },
                error: function (request, status, error) {
                    alert("error " + request.responseText);
                }
            });
        });
    });
</script>
<input type="checkbox" value="ALFKI" />ALFKI<br />
<input type="checkbox" value="BOLID" />BOLID<br />
<input type="checkbox" value="BOTTM" />BOTTM<br />
<input type="button" name="command" id="btnGetChecks" value="Generate Selected" />
bigbear
 
on Nov 07, 2019 09:20 AM
on Nov 07, 2019 09:21 AM

YOU DID ITTT!~!!!~!!@#!#!@#!@#! WWOO0000tttttt

I completed reconstructed my methods like you i used "GET" instead of "POST" because for some reason my project isn't letting my use POST But I got it working both PDFs are as they are suppose to be in the zip now.

I created a Model like you and thats how i did it.

 [HttpGet]
   public virtual ActionResult DownloadAsZip(string mimeType)
   {          
       if (TempData["Files"] != null)
       {
           List<ServiceFile> lstFiles = TempData["Files"] as List<ServiceFile>;
           byte[] bytearray = null;

           using (MemoryStream ms = new MemoryStream())
           {
               // Creates the .zip
               using (ZipArchive archive = new ZipArchive(ms, ZipArchiveMode.Create, true))
               {
                   foreach (ServiceFile file in lstFiles)  // iterate through each file
                   {
                       // Creates empty file and names it inside of .zip
                       ZipArchiveEntry zipItem = archive.CreateEntry(file.FileName + file.Extension);
                       // adds file to zipItem
                       using (MemoryStream ms4file = new MemoryStream(file.FileBytes))
                       {
                           using (Stream stream = zipItem.Open())
                           {
                               ms4file.CopyTo(stream);
                           }
                       }
                   }
               }
               bytearray = ms.ToArray();
           }
           return File(bytearray, "application/zip");
       }
       else
       {
           return new EmptyResult();
       }
   }
        public ActionResult ExportFiles(int[] quoteIDs)
        {
            List<ServiceFile> lstFiles = new List<ServiceFile>();
            if (quoteIDs != null)
            {
                string command = "PDF";
                string reportType = command;
                string mimeType = "", encoding = "", fileNameExtension = "";

                foreach (var qid in quoteIDs)
                {
                    List<ServiceQuote> lstQuotes = new List<ServiceQuote>();
                    var quote = context.ServiceQuotes.Where(x => x.QuoteID == qid).FirstOrDefault();
                    lstQuotes.Add(quote);

                    LocalReport localReport = new LocalReport()
                    {
                        ReportPath = Server.MapPath("~/ReportForms/VirtualService3.rdlc")
                    };
                    ReportDataSource reportDataSource = new ReportDataSource("Service_Fields", lstQuotes);
                    localReport.DataSources.Add(reportDataSource);

                    string deviceInfo =
                                    "<DeviceInfo>" +
                                    "   <OutputFormat>" + reportType + "</OutputFormat>" +
                                    "   <PageWidth>8.5in</PageWidth>" +
                                    "   <PageHeight>11in</PageHeight>" +
                                    "   <MarginTop>0in</MarginTop>" +
                                    "   <MarginLeft>0in</MarginLeft>" +
                                    "   <MarginRight>0in</MarginRight>" +
                                    "   <MarginBottom>0in</MarginBottom>" +
                                    "</DeviceInfo>";
                    Warning[] warnings;
                    string[] streams;
                    byte[] renderedBytes = localReport.Render(reportType, deviceInfo, out mimeType, out encoding,
                                                                out fileNameExtension, out streams, out warnings);
                    lstFiles.Add(new ServiceFile { Extension = "." + fileNameExtension, FileName = qid.ToString(), FileBytes = renderedBytes });                   
                }
                TempData["Files"] = lstFiles;

                //return new JsonResult() { Data = new { MimeType = mimeType } };
                return Json(mimeType, JsonRequestBehavior.AllowGet);
                //return File(renderedBytes, mimeType);
            }

            return RedirectToAction("VirtualService");
        }