Asked by:
Memory leak with multiple PDF report generation

Question
-
Hi,
In our MVC application, provided multi print PDF option to users using "Microsoft.Reporting.WebForms" and "iTextSharp" . Functionality working as expected but its observed that Huge memory leak (50 MB-200MB) happens with every print.
Attached the code for reference. Request help on priority basis.
Thanks,
Siva
using iTextSharp.text; using iTextSharp.text.pdf; using Microsoft.Reporting.WebForms; using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Linq; using System.Web.Mvc; public class InvoicePrintGSTController : BaseController { readonly IInvoicePrintGSTRepository invGSTRepo; readonly IInvoicePrintRepository invRepo; readonly ISalesOrderDeliveryRepository iSalesOrderDeliveryRepository; public InvoicePrintGSTController(IInvoicePrintGSTRepository invGSTRepo, IInvoicePrintRepository invRepo, ISalesOrderDeliveryRepository iSalesOrderDeliveryRepository) { this.invGSTRepo = invGSTRepo; this.invRepo = invRepo; this.iSalesOrderDeliveryRepository = iSalesOrderDeliveryRepository; } // GET: SalesOrderDelivery/InvoicePrintGST public JsonResult GeneratePdfForMultipleRecord(DeliveryReturnHDR DelRtn, string format) { DataTable PrintInfo = new DataTable(); PrintInfo.Columns.Add("InvoiceDocNo"); PrintInfo.Columns.Add("InvoiceTransCode"); string[] InvoiceDetails; for (int i = 0; i < DelRtn.SelectedInvoices.Length; i++) { InvoiceDetails = DelRtn.SelectedInvoices[i].Split(','); if (InvoiceDetails[0] != "Invoice No.") { DataRow Dr = PrintInfo.NewRow(); Dr["InvoiceDocNo"] = InvoiceDetails[0]; Dr["InvoiceTransCode"] = InvoiceDetails[1]; bool Return = invGSTRepo.SavePrintHistory(InvoiceDetails[0].ConvertObjectToString(), InvoiceDetails[1].ConvertObjectToString(), UserInfo.UserId); PrintInfo.Rows.Add(Dr); } } using (PrintInfo) { //DataTable InvPrint = new DataTable(); string InvoiceDocNo = ""; string returnUrl = string.Empty; string filePath_ = string.Empty; string InvoiceTransCode = ""; string InvoiceStateReport = ""; byte[] renderedBytes = null; LocalReport reportTemp = new LocalReport(); //Array ByteList = Array.CreateInstance(typeof(byte[]), PrintInfo.Rows.Count); DataSet DS_ReportDetails = new DataSet(); string CalMethod = string.Empty; //string StrFileName = "InvoicePrintReport" + System.DateTime.Now.ToString("ddMMyyyyHHmmssfff") + ".pdf"; string StrFileName = string.Concat("InvoicePrintReportGst_", UserInfo.UserId, "_", System.DateTime.Now.Ticks); List<string> fileNames = new List<string>(); int index = 0; if (PrintInfo != null) { foreach (DataRow Rows in PrintInfo.Rows) { LocalReport report = new LocalReport(); string deviceInfo = string.Empty; InvoiceDocNo = Rows["InvoiceDocNo"].ToString(); InvoiceTransCode = Rows["InvoiceTransCode"].ToString(); if (format == "A4") { InvoiceStateReport = "GSTInvoiceGTA4.rdlc"; } else { InvoiceStateReport = "GSTInvoiceGTA5.rdlc"; } invGSTRepo.GenerateSecInvoiceRPTGST(InvoiceDocNo, InvoiceTransCode, out DS_ReportDetails); #region ReportBinding using (DS_ReportDetails) { if (DS_ReportDetails.Tables[0].Rows.Count > 0) { if (DS_ReportDetails.Tables[0].Rows[0]["CalMethod"].ToString().Trim() == "M1" || DS_ReportDetails.Tables[0].Rows[0]["CalMethod"].ToString().Trim() == "M2" || DS_ReportDetails.Tables[0].Rows[0]["CalMethod"].ToString().Trim() == "M3" || DS_ReportDetails.Tables[0].Rows[0]["CalMethod"].ToString().Trim() == "M4") { if (Convert.ToString(Session["A5"]) == string.Empty) { InvoiceStateReport = "GSTInvoiceMTA4.rdlc"; CalMethod = "MT"; } else { InvoiceStateReport = "GSTInvoiceMTA5.rdlc"; CalMethod = "MT"; } } else { CalMethod = string.Empty; } } if (DS_ReportDetails != null) { if (DS_ReportDetails.Tables[0].Rows.Count > 0) { report.ReportPath = Server.MapPath("~/PrintReports/InvoicePrintGST/" + Convert.ToString(InvoiceStateReport)); string imagePath = string.Empty; report.EnableExternalImages = true; if (DS_ReportDetails.Tables[0].Rows[0]["INVOICECANCELSTATUS"].ToString() == "1") { if (Convert.ToString(Session["InvFormat"]) == "A4") { if (!String.IsNullOrEmpty(Convert.ToString(DS_ReportDetails.Tables[0].Rows[0]["Retailer_TINNo"]))) { imagePath = new Uri(Server.MapPath("~/Images/ITAXINVOICECANCELLEDA4.jpg")).AbsoluteUri; } else { imagePath = new Uri(Server.MapPath("~/Images/IRETAILINVOICECANCELLEDA4.jpg")).AbsoluteUri; } } else { if (!String.IsNullOrEmpty(Convert.ToString(DS_ReportDetails.Tables[0].Rows[0]["Retailer_TINNo"]))) { imagePath = new Uri(Server.MapPath("~/Images/ITAXINVOICECANCELLEDA5.jpg")).AbsoluteUri; } else { imagePath = new Uri(Server.MapPath("~/Images/IRETAILINVOICECANCELLEDA5.jpg")).AbsoluteUri; } } } else { if (Convert.ToString(Session["InvFormat"]) == "A4") { imagePath = new Uri(Server.MapPath("~/Images/InvoiceCancel_BlankA4.jpg")).AbsoluteUri; } else { imagePath = new Uri(Server.MapPath("~/Images/InvoiceCancel_BlankA5.jpg")).AbsoluteUri; } } ReportParameter parameter = new ReportParameter("InvoiceImage", imagePath); report.SetParameters(parameter); report.DataSources.Add(new ReportDataSource("Calculation", DS_ReportDetails.Tables[2])); //DataSourceCal report.DataSources.Add(new ReportDataSource("Header", DS_ReportDetails.Tables[0])); // DataSourceHeader report.DataSources.Add(new ReportDataSource("Detail", DS_ReportDetails.Tables[1])); //DataSourceInvoice report.DataSources.Add(new ReportDataSource("Visibility", DS_ReportDetails.Tables[3])); //DataSourceVisibility report.DataSources.Add(new ReportDataSource("Voucher", DS_ReportDetails.Tables[4])); // DataSourceVoucher report.DataSources.Add(new ReportDataSource("Incentive", DS_ReportDetails.Tables[5])); //DataSourceIncentive report.DataSources.Add(new ReportDataSource("ArticleScheme", DS_ReportDetails.Tables[6])); //DataSourceArticle #endregion } } if (format == "A4") { if (CalMethod == "MT") { deviceInfo = CommonUtilities.MTA4PageConfig; } else { deviceInfo = CommonUtilities.NonMTA4PageConfig; } } else { if (CalMethod == "MT") { deviceInfo = CommonUtilities.MTA5PageConfig; } else { //deviceInfo = CommonUtilities.NonMTA5PageConfig; deviceInfo = "<DeviceInfo>" + " <OutputFormat>EMF</OutputFormat>" + " <PageWidth>8.27in</PageWidth>" + " <PageHeight>5.83in</PageHeight>" + " <MarginTop>0.05in</MarginTop>" + " <MarginLeft>0.05in</MarginLeft>" + " <MarginRight>0.05in</MarginRight>" + " <MarginBottom>0.05in</MarginBottom>" + "</DeviceInfo>"; } } renderedBytes = report.Render(CommonUtilities.ReportType, deviceInfo); System.IO.File.WriteAllBytes(Path.Combine(CommonUtilities.InvoiceFolderPath, StrFileName + "_" + index + CommonUtilities.FileExtension), renderedBytes); fileNames.Add(Path.Combine(CommonUtilities.InvoiceFolderPath, StrFileName + "_" + index + CommonUtilities.FileExtension)); index++; } } filePath_ = CommonUtilities.InvoiceFilePathConstant + StrFileName + CommonUtilities.FileExtension; if (MergePDFs(fileNames, Path.Combine(CommonUtilities.InvoiceFolderPath, StrFileName + CommonUtilities.FileExtension))) { returnUrl = filePath_; } } else { InvoiceDocNo = Convert.ToString(Session["InvoiceDocNo"]); InvoiceTransCode = Convert.ToString(Session["InvTranCode"]); string StrCustomerCode = Session["RetailerCode"] == null ? "" : Session["RetailerCode"].ToString(); if (StrCustomerCode != "CSO_Dummy") { invGSTRepo.GenerateSecInvoiceRPTGST(InvoiceDocNo, InvoiceTransCode, out DS_ReportDetails); } else { invGSTRepo.GenerateSecInvoiceRPT_CounterOrderGST(InvoiceDocNo, InvoiceTransCode, out DS_ReportDetails); } #region ReportBinding using (DS_ReportDetails) { if (DS_ReportDetails.Tables[0].Rows.Count > 0) { if (DS_ReportDetails.Tables[0].Rows[0]["CalMethod"].ToString().Trim() == "M1" || DS_ReportDetails.Tables[0].Rows[0]["CalMethod"].ToString().Trim() == "M2" || DS_ReportDetails.Tables[0].Rows[0]["CalMethod"].ToString().Trim() == "M3" || DS_ReportDetails.Tables[0].Rows[0]["CalMethod"].ToString().Trim() == "M4") { if (Convert.ToString(Session["A5"]) == string.Empty) { InvoiceStateReport = "GSTInvoiceMTA4.rdlc"; CalMethod = "MT"; } else { InvoiceStateReport = "GSTInvoiceMTA5.rdlc"; CalMethod = "MT"; } } else { CalMethod = string.Empty; } } if (DS_ReportDetails != null) { if (DS_ReportDetails.Tables[0].Rows.Count > 0) { reportTemp.ReportPath = Server.MapPath("~/PrintReports/InvoicePrintGST/" + Convert.ToString(InvoiceStateReport)); string imagePath = string.Empty; reportTemp.EnableExternalImages = true; if (DS_ReportDetails.Tables[0].Rows[0]["INVOICECANCELSTATUS"].ToString() == "1") { if (Convert.ToString(Session["InvFormat"]) == "A4") { if (!String.IsNullOrEmpty(Convert.ToString(DS_ReportDetails.Tables[0].Rows[0]["Retailer_TINNo"]))) { imagePath = new Uri(Server.MapPath("~/Images/ITAXINVOICECANCELLEDA4.jpg")).AbsoluteUri; } else { imagePath = new Uri(Server.MapPath("~/Images/ITAXINVOICECANCELLEDA4.jpg")).AbsoluteUri; } } else { if (!String.IsNullOrEmpty(Convert.ToString(DS_ReportDetails.Tables[0].Rows[0]["Retailer_TINNo"]))) { imagePath = new Uri(Server.MapPath("~/Images/ITAXINVOICECANCELLEDA5.jpg")).AbsoluteUri; } else { imagePath = new Uri(Server.MapPath("~/Images/ITAXINVOICECANCELLEDA4.jpg")).AbsoluteUri; } } } else { if (Convert.ToString(Session["InvFormat"]) == "A4") { imagePath = new Uri(Server.MapPath("~/Images/InvoiceCancel_BlankA4.jpg")).AbsoluteUri; } else { imagePath = new Uri(Server.MapPath("~/Images/InvoiceCancel_BlankA5.jpg")).AbsoluteUri; } } ReportParameter parameter = new ReportParameter("InvoiceImage", imagePath); reportTemp.SetParameters(parameter); reportTemp.DataSources.Add(new ReportDataSource("Calculation", DS_ReportDetails.Tables[2])); //DataSourceCal reportTemp.DataSources.Add(new ReportDataSource("Header", DS_ReportDetails.Tables[0])); // DataSourceHeader reportTemp.DataSources.Add(new ReportDataSource("Detail", DS_ReportDetails.Tables[1])); //DataSourceInvoice reportTemp.DataSources.Add(new ReportDataSource("Visibility", DS_ReportDetails.Tables[3])); //DataSourceVisibility reportTemp.DataSources.Add(new ReportDataSource("Voucher", DS_ReportDetails.Tables[4])); // DataSourceVoucher reportTemp.DataSources.Add(new ReportDataSource("Incentive", DS_ReportDetails.Tables[5])); //DataSourceIncentive reportTemp.DataSources.Add(new ReportDataSource("ArticleScheme", DS_ReportDetails.Tables[6])); //DataSourceArticle #endregion } } #region PageFormatSetting string deviceInfo = string.Empty; if (Convert.ToString(Session["InvFormat"]) == "A4") { deviceInfo = CommonUtilities.NonMTA4PageConfig; } else { if (CalMethod == "MT") { deviceInfo = CommonUtilities.MTA5PageConfig; } else { deviceInfo = CommonUtilities.NonMTA5PageConfig; } } renderedBytes = reportTemp.Render(CommonUtilities.ReportType, deviceInfo); filePath_ = CommonUtilities.InvoiceFilePathConstant + StrFileName; //string filePath = Path.Combine(FolderPath, StrFileName); if (!(Directory.Exists(CommonUtilities.InvoiceFolderPath))) Directory.CreateDirectory(CommonUtilities.InvoiceFolderPath); System.IO.File.WriteAllBytes(Path.Combine(CommonUtilities.InvoiceFolderPath, StrFileName), renderedBytes); returnUrl = filePath_; } #endregion } if (renderedBytes != null && renderedBytes.Length > 0) Array.Clear(renderedBytes, 0, renderedBytes.Length); renderedBytes = null; fileNames.TrimExcess(); fileNames = null; return Json(returnUrl, JsonRequestBehavior.AllowGet); } } public static bool MergePDFs(IEnumerable<string> fileNames, string targetPdf) { bool merged = true; using (FileStream stream = new FileStream(targetPdf, FileMode.Create)) { Document document = new Document(); PdfCopy pdf = new PdfCopy(document, stream); PdfReader reader = null; try { document.Open(); foreach (string file in fileNames) { reader = new PdfReader(file); pdf.AddDocument(reader); reader.Close(); } } catch (Exception) { merged = false; if (reader != null) { reader.Close(); } } finally { if (document != null) { document.Close(); } } } return merged; } }
Sivananda Vanukuri
- Moved by CoolDadTx Thursday, June 21, 2018 2:10 PM ASP.NET related
Thursday, June 21, 2018 11:03 AM
All replies
-
Please post questions related to web development in the ASP.NET forums.
Please post issues related to third party products like iTextSharp in their forums.
Michael Taylor http://www.michaeltaylorp3.net
Thursday, June 21, 2018 2:10 PM