Generate (Download) separate PDF report for each record using RDLC in ASP.Net MVC

bigbear
 
on Nov 01, 2019 12:20 AM
Sample_499916.zip
1859 Views

Hello everyone,

I have a list of records, When I went to put my list in as a report data source to my rdlc report it said my datasource must be a data table or 2 other options it gave. I turned my list into a datatable and now when I insert that as my data source I get no errors and my controller action completes but my return file never opens up a new report or anything for my record.

If I try to just insert 1 record I get the report opened as an rdlc report.

is there a way with you selecting those checkboxes that it could open 2 windows 1 for each record selected? I am eventually going to have to generate a seperate report for each selected record.

        <input type="button" class="btn btn-primary" name="command" id="btnGetChecks" value="Generate Selected" />
        $('#btnGetChecks').on('click', function () {
            var arrChkBoxes = [];
            var arrSelectedQIDs = [];
            var quoteid = $(this).attr("value");
            var chkboxtable = $('#maintbl');
            var chktablebody = chkboxtable.find('#maintblbody');
            $("input:checked").each(function (index, value) {
                arrChkBoxes.push($(value).val());
            });
            // Push all QuoteIDs into new array
            $.each(arrChkBoxes, function (key, value) {
                if (IsPositiveInteger(value)) {
                    arrSelectedQIDs.push(value);
                }
            });

            $.ajax({
                type: "GET",
                url: "/Service/GeneratePreviewReports/",
                contentType: "application/json; charset=utf-8",
                traditional: true,
                data: { "quoteIDs": arrSelectedQIDs },
                success: function () {
                    alert("success");
                },
                error: function (request, status, error) {
                    alert("error " + request.responseText);
                }
            });
            //alert(arrSelectedQIDs);
        });        

 

        public ActionResult GeneratePreviewReports(int[] quoteIDs)
        {
            List<ServiceQuote> lstQuotes = new List<ServiceQuote>();
            // servicequote same fields as 'Service_Fields'
            //for(int i=0; i<quoteIDs.Length-1; i++)
            //{ var quote = context.ServiceQuotes.Where(x => x.QuoteID == quoteIDs[i]).fi }
            if(quoteIDs != null)
            {
                foreach(var qid in quoteIDs)
                {
                    var quote = context.ServiceQuotes.Where(x => x.QuoteID == qid).FirstOrDefault();
                    lstQuotes.Add(quote);
                }
            }

            //TRACKER_TESTDataSetTableAdapters.Service_FieldsTableAdapter tableAdapter = new TRACKER_TESTDataSetTableAdapters.Service_FieldsTableAdapter();
            LocalReport localReport = new LocalReport()
            {
                ReportPath = Server.MapPath("~/ReportForms/VirtualService3.rdlc")
            };
            List<TRACKER_TESTDataSet.Service_FieldsRow> rows = new List<TRACKER_TESTDataSet.Service_FieldsRow>();

            foreach(var item in lstQuotes)
            {
                var itemTable = CreateDT(item);//CreateDataTable(item);
                // rows.Add(tableAdapter.Fill(item))
                ReportDataSource reportDataSource = new ReportDataSource("Service_Fields", itemTable);
                localReport.DataSources.Add(reportDataSource);
                // command specifies whether its a PDF EXCEL WORD IMAGE doc
                string command = "PDF";
                string reportType = command;
                string mimeType, encoding, fileNameExtension;
                string deviceInfo =
                    "<DeviceInfo>" +
                    "   <OutputFormat>" + command + "</OutputFormat>" +
                    "   <PageWidth>8.5in</PageWidth>" +
                    "   <PageHeight>11in</PageHeight>" +
                    "   <MarginTop>0.5in</MarginTop>" +
                    "   <MarginLeft>0.3in</MarginLeft>" +
                    "   <MarginRight>0.3in</MarginRight>" +
                    "   <MarginBottom>0.5</MarginBottom>" +
                    "</DeviceInfo>";

                Warning[] warnings;
                string[] streams;
                byte[] renderedBytes;
                renderedBytes = localReport.Render(reportType, deviceInfo, out mimeType, out encoding, out fileNameExtension, out streams, out warnings);
                return File(renderedBytes, mimeType);
            }

            return RedirectToAction("VirtualService");
        }

        private DataTable CreateDT(object obj)
        {
            if(obj != null)
            {
                Type t = obj.GetType();
                DataTable dt = new DataTable(t.Name);
                foreach(PropertyInfo pi in t.GetProperties())
                {
                    dt.Columns.Add(new DataColumn(pi.Name));
                }
                DataRow dr = dt.NewRow();
                foreach(DataColumn dc in dt.Columns)
                {
                    dr[dc.ColumnName] = obj.GetType().GetProperty(dc.ColumnName).GetValue(obj, null);
                }
                dt.Rows.Add(dr);
                return dt;
            }
            return null;
        }

 

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Nov 01, 2019 07:30 AM
on Nov 01, 2019 08:24 AM

Hi bigbear,

There is no need to convert to DataTable. You can pass the List to the ReportDataSource.

Check this example. Now please take its reference and correct your code.

Database

For this example I have used of Northwind database that you can download using the link given below.

Download Northwind Database

Namespaces

using System.Collections.Generic;
using System.IO;
using System.Linq;
using Ionic.Zip;
using Microsoft.Reporting.WebForms;

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 Download(string mimeType)
    {
        if (TempData["Data"] != null)
        {
            List<byte[]> bytesArray = TempData["Data"] as List<byte[]>;
            List<string> fileNames = TempData["File"] as List<string>;

            using (ZipFile zip = new ZipFile())
            {
                zip.AlternateEncodingUsage = ZipOption.AsNecessary;
                int i = 0;
                foreach (byte[] bytes in bytesArray)
                {
                    zip.AddEntry(fileNames[i], bytes);
                    i++;
                }
                string zipName = String.Format("Zip_{0}.zip", DateTime.Now.ToString("yyyy-MMM-dd-HHmmss"));
                using (MemoryStream memoryStream = new MemoryStream())
                {
                    zip.Save(memoryStream);
                    return File(memoryStream.ToArray(), "application/zip", zipName);
                }
            }
        }
        else
        {
            return new EmptyResult();
        }
    }
}

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: { "quoteIDs": arrSelectedQIDs },
                success: function (data) {
                    window.location = '/Home/Download?filename=' + data.MimeType;
                },
                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" />

This will generate zip file containg each record as separate pdf file.

For zip file i have used below article.

Create ZIP File in ASP.Net MVC