RDLC生成pdf文件“An unexpected error occurred in Report Processing”错误处理

这几天遇到一个简单又纠结的异常:

通过循环报表生成pdf文件的时候,循环时出现了一个错误:“An unexpected error occurred in Report Processing”发生在行:

“byte[] bytes = reportViewMain.LocalReport.Render(fileFormat, null, out strMimeType, out strEncoding, out strFileNameExtension, out strStreamIds, out warnings);”
这个问题主要是循环同一个rdlc模板的时候出现的,第一个报表生成pdf文件成功,但是第二个报表生成的时候就报错了,我也尝试通过:“reportViewMain.LocalReport.Dispose();”释放资源,但是没用。

积极查找信息,并解决中....

通过参考:http://hi.baidu.com/jiangdbna/item/d8063f612f9da72f68105b13

因为在循环中有资源没有释放,所以必须通过:

reportViewMain.Reset();  //将控件重置为其默认值(reportViewMain为ReportViewer控件名)

即可。

 

关键性代码参考如下:

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Reflection;
using System.IO;
using TlEt.Ss.Model.SsSys;
using System.Configuration;
using Microsoft.Reporting.WebForms;

using System.Text;
using System.Drawing.Imaging;
using System.Drawing.Printing;
using System.Threading;

using TlEt.Ss.Common;
using TlEt.Ss.UILogic;
using TlEt.Ss.Model;
using TlEt.Ss.Model.Reports;
using TlEt.Ss.BLL;
using TlEt.Framework.Cache;
using System.Security;
using System.Security.Permissions;

namespace TlEt.Ss.Web.Common
{
    public partial class MultiReportPreview : PageBase, IDisposable
    {
        private IList<TlEt.Ss.Model.Report> subReports;

        private int printCurrentPageIndex; //记录打印的页索引
        private IList<Stream> printStreams; //打印的数据流

        private string path = UIUtilities.GetConfigValue<string>("ReportPath");
        private string forSpecimen = UIUtilities.GetConfigValue<string>("ForSpecimen");
        bool isExists = false;

        string emailAttachmentsPath
        {
            get
            {
                string attachPath = ConfigurationManager.AppSettings["EmailAttachmentsPath"];
                attachPath = AppDomain.CurrentDomain.BaseDirectory + attachPath.Replace("/","\\");

                if (!Directory.Exists(attachPath))
                {
                    Directory.CreateDirectory(attachPath);
                }

                return attachPath;
            }
        }
        string reportPreviewPath
        {
            get
            {
                string filePath = ConfigurationManager.AppSettings["ReportPreviewPath"];
                filePath = AppDomain.CurrentDomain.BaseDirectory + filePath.Replace("/", "\\");

                if (!Directory.Exists(filePath))
                {
                    Directory.CreateDirectory(filePath);
                }

                return filePath;
            }
        }

        private string splitUrl = "";
        private string[] pdflist;
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (!this.IsPostBack)
                {
                    SetReportSize();

                    string tempReportPath = string.Empty;
                    string url = Request.RawUrl.ToString();
                    string strUrl = url.Substring(url.IndexOf("?") + 1, url.Length - url.IndexOf("?") - 1);
                    string[] strTemp = strUrl.Split('/');
                    if (strTemp.Length > 0)
                    {
                        pdflist = new string[strTemp.Length];

                        for (int m = 0; m < strTemp.Length; m++)
                        {
                            splitUrl = strTemp[m].ToString();
                            string[] parameters = splitUrl.Split('&');

                            string reportID = parameters[1].Substring(9, parameters[1].Length - 9);//Request.QueryString["ReportID"].ToString();
                            string reportFolder = parameters[0].Substring(13, parameters[0].Length - 13);//Request.QueryString["ReportFolder"].ToString();

                            string configFile = Server.MapPath(UIUtilities.ApplicationPath + "/Config/" + reportFolder + "Reports.xml");
                            TlEt.Ss.Model.Report report = ReportUtility.GetReportsByID(configFile, reportID);

                            if (report == null)
                            {
                                Response.Write("Could not find report: " + reportID);
                                Response.End();
                                return;
                            }

                            if (path.Substring(path.Length - 1) != @"\") path = path + @"\";

                            reportViewMain.Reset();
                            Microsoft.Reporting.WebForms.ReportParameter[] reportParas = GetReportParas(report);
                            reportViewMain.LocalReport.ReportPath = path + report.Path;
                            if (reportParas != null) reportViewMain.LocalReport.SetParameters(reportParas);
                            reportViewMain.LocalReport.DataSources.Clear();

                            if (report.DataSources != null)
                            {
                                for (int i = 0; i < report.DataSources.Count; i++)
                                {
                                    Dictionary<string, string> methodParas = GetMethodParas(report.DataSources[i], GetUrlParas(splitUrl));
                                    //反射调用
                                    IEnumerable<Object> ds = ReportUtility.GetDataSource(report.DataSources[i], methodParas);

                                    if (i == 0 || report.DataSources[i].Name.IndexOf("Header") > 0) SetReportDefaultValue(ref ds);

                                    ReportDataSource rds = new ReportDataSource(report.DataSources[i].Name, ds);
                                    reportViewMain.LocalReport.DataSources.Add(rds);
                                }
                            }

                            //reportViewMain.LocalReport.Refresh();

                            //是否有子报表
                            if (report.SubReports != null)
                            {
                                subReports = report.SubReports;
                                reportViewMain.LocalReport.SubreportProcessing += new Microsoft.Reporting.WebForms.SubreportProcessingEventHandler(LocalReport_SubreportProcessing);
                            }

                            //导出报表
                            string action = Request.QueryString["action"];
                            if (!string.IsNullOrEmpty(action))
                            {
                                string message = string.Empty;
                                if (action == "sendemail")
                                {
                                    string attachFormat = Request.QueryString["attachFormat"]; //0:PDF,1:JPG,2:Excel
                                    message = CreatePDF(attachFormat, emailAttachmentsPath.Replace("\\\\", "\\"));
                                }

                                //生成PDF,用于报表预览
                                else if (action == "previewpdf")
                                {
                                    string attachFormat = "0"; //0:PDF
                                    message = CreatePDF(attachFormat, reportPreviewPath.Replace("\\\\", "\\"));
                                    if (!string.IsNullOrEmpty(message))
                                    {
                                        pdflist[m] = message;
                                    }
                                }

                                //不弹出打印选项,直接打印(已停用)
                                else if (action == "print")
                                {
                                    ExportForPrint(reportViewMain.LocalReport);

                                    printCurrentPageIndex = 0;
                                    Print(ref message);
                                }


                                this.ScriptManager1.Dispose();
                                this.reportViewMain.LocalReport.Dispose();
                                this.reportViewMain.LocalReport.DataSources.Clear();

                            }
                        }
                        CombinePDF combinePDF = new CombinePDF();
                        string fileName = DateTime.Now.ToString("yyyyMMddHHmmssffff") + ".pdf";
                        bool isCombineSuccess = combinePDF.mergePDFFiles(pdflist, reportPreviewPath + fileName);
                        Response.Clear();
                        Response.Write(fileName + "|");
                    }
                }
            }
            catch (Exception ex)
            {
                Response.Write("NULL!");
                LoggerManager.WriteSysLog.Fatal("ReporePreview Error:" + ex.Message);
            }
        }

        private void SetReportSize()
        {
            string rWidth = Request.QueryString["rWidth"];
            string rHeight = Request.QueryString["rHeight"];

            if (!string.IsNullOrEmpty(rWidth) && !string.IsNullOrEmpty(rHeight))
            {
                reportViewMain.Width = Unit.Parse(rWidth + "px");
                reportViewMain.Height = Unit.Parse(rHeight + "px");
            }
        }

        private void LocalReport_SubreportProcessing(object sender, Microsoft.Reporting.WebForms.SubreportProcessingEventArgs e)
        {
            TlEt.Ss.Model.Report report = GetReport(subReports, e.ReportPath);

            if (report != null && report.DataSources != null)
            {
                foreach (var datasource in report.DataSources)
                {
                    Dictionary<string, string> methodParas = GetMethodParas(datasource, GetUrlParas(splitUrl));
                    IEnumerable<Object> ds = ReportUtility.GetDataSource(datasource, methodParas);
                    e.DataSources.Add(new ReportDataSource(datasource.Name, ds));
                }
            }
        }

        private TlEt.Ss.Model.Report GetReport(IList<Model.Report> _subReports, string reportPath)
        {
            isExists = false;
            TlEt.Ss.Model.Report _report = null;
            foreach (TlEt.Ss.Model.Report report in _subReports)
            {
                if (isExists)
                {
                    break;
                }

                if (report.Path != null && report.Path.Contains(reportPath))
                {
                    isExists = true;
                    return report;
                }

                if (report.SubReports != null && !isExists)
                {
                    _report = GetReport(report.SubReports, reportPath);
                }
            }
            return _report;
        }

        private void SetReportDefaultValue(ref IEnumerable<Object> ds)
        {
            string userID = UISessionManager.CurrentUser.UserID;
            string userName = UISessionManager.CurrentUser.UserName;
            string companyName = UISessionManager.CurrentUser.CompanyName;
            string companyNo = UISessionManager.CurrentUser.CompanyNo;

            //string userID = "TC1";
            //string userName = "Travel Consultant";
            //string companyName = "Travel Expert Limit";
            //string companyNo = "TEL";

            OrgUnit_MasterImpl orgBLL = new OrgUnit_MasterImpl();
            OrgUnit_Master orgUnit = orgBLL.Load(companyNo, userID);
            object companyLogo = orgUnit.CompanyLogo;
            object companyLogo1 = orgUnit.CompanyLogo1;//页脚图片

            foreach (object o in ds)
            {
                bool isInheriteFromBaseModel = o is RPTBaseModel;

                if (isInheriteFromBaseModel)
                {
                    PropertyInfo pCompanyName = o.GetType().GetProperty("CompanyName");
                    if (pCompanyName != null) pCompanyName.SetValue(o, companyName, null);

                    PropertyInfo pCompanyLogo = o.GetType().GetProperty("CompanyLogo");
                    if (pCompanyLogo != null)
                    {
                        pCompanyLogo.SetValue(o, companyLogo, null);
                    }

                    PropertyInfo pPrintUser = o.GetType().GetProperty("PrintUser");
                    if (pPrintUser != null) pPrintUser.SetValue(o, userName, null);

                    PropertyInfo pPrintDate = o.GetType().GetProperty("PrintDate");
                    if (pPrintDate != null) pPrintDate.SetValue(o, Utility.FormatDate(DateTime.Now), null);

                    PropertyInfo pPrintTime = o.GetType().GetProperty("PrintTime");
                    if (pPrintTime != null)
                    {
                        string m = DateTime.Now.ToString("hh:mm");

                        if (DateTime.Now.Hour > 11) 
                            m+= " PM";
                        else
                            m += " AM";

                        pPrintTime.SetValue(o, m, null);
                    }

                    PropertyInfo pIsDisplayFooterImage = o.GetType().GetProperty("IsDisplayFooterImage");
                    if (pIsDisplayFooterImage != null)
                    {
                        object val = pIsDisplayFooterImage.GetValue(o, null);

                        if (val != null && (bool)val)
                        {
                            PropertyInfo pFooterImage = o.GetType().GetProperty("FooterImage");
                            if (pFooterImage != null)
                            {
                                //pFooterImage.SetValue(o, FooterData, null); old
                                pFooterImage.SetValue(o, companyLogo1, null); //new
                            }
                        }
                    }

                    PropertyInfo pIsDisplayVoidImage = o.GetType().GetProperty("IsDisplayVoidImage");
                    if (pIsDisplayVoidImage != null)
                    {
                        object val = pIsDisplayVoidImage.GetValue(o, null);

                        if (val != null && (bool)val)
                        {
                            PropertyInfo pVoidImage = o.GetType().GetProperty("VoidImage");
                            if (pVoidImage != null)
                            {
                                pVoidImage.SetValue(o, VoidData, null);
                            }
                        }
                    }

                    if (forSpecimen == "Y")
                    {
                        PropertyInfo pSpecimenImage = o.GetType().GetProperty("SpecimenImage");
                        if (pSpecimenImage != null)
                        {
                            pSpecimenImage.SetValue(o, SpecimenData, null);
                        }
                    }
                }

                break;
            }
        }

        private Dictionary<string, string> GetUrlParas(string CurrUrl)
        {
            Dictionary<string, string> paras = new Dictionary<string, string>();

            string[] parameters = CurrUrl.Split('&');

            foreach (string str in parameters)
            {
                string[] s = str.Split('=');
                paras.Add(s[0], s[1]);
            }

            return paras;

        }

        private Dictionary<string, string> GetMethodParas(DataSource report,Dictionary<string, string> paras)
        {
            if (report.MethodParameters == null)
            {
                return null;
            }
            else
            {
                Dictionary<string, string> methodParas = new Dictionary<string, string>();

                foreach (var methodPara in report.MethodParameters)
                {
                    if (Request.QueryString[methodPara.ParaName] != null)
                    {
                        methodParas.Add(methodPara.ParaName.ToLower(), paras[methodPara.ParaName]);
                    }
                }

                if (methodParas.Count <= 0)
                    return null;
                else
                    return methodParas;
            }
        }

        private Microsoft.Reporting.WebForms.ReportParameter[] GetReportParas(TlEt.Ss.Model.Report report)
        {
            if (report.ReportParameters == null)
            {
                return null;
            }
            else
            {
                int i = 0;

                foreach (var reportPara in report.ReportParameters) if (Request.QueryString[reportPara.ParaName] != null || reportPara.ParaValue!="") i++;
                Microsoft.Reporting.WebForms.ReportParameter[] reportParas = new Microsoft.Reporting.WebForms.ReportParameter[i];

                i = 0;
                foreach (var reportPara in report.ReportParameters)
                {
                    if (Request.QueryString[reportPara.ParaName] != null)
                    {
                        Microsoft.Reporting.WebForms.ReportParameter para = new Microsoft.Reporting.WebForms.ReportParameter(reportPara.ParaName);
                        para.Values.Add(Request.QueryString[reportPara.ParaName].ToString());
                        reportParas[i++] = para;
                    }
                    else
                    {
                        Microsoft.Reporting.WebForms.ReportParameter para = new Microsoft.Reporting.WebForms.ReportParameter(reportPara.ParaName);
                        para.Values.Add(reportPara.ParaValue);
                        reportParas[i++] = para;
                    }
                }

                if (reportParas.Length <= 0)
                    return null;
                else
                    return reportParas;
            }
        }

        public string CreatePDF(string fileType,string savePath)
        {
            string fileFormat = string.Empty;
            string fileExtension = string.Empty;
            GetFileFormat(fileType, ref fileFormat, ref fileExtension);

            string fileName = DateTime.Now.ToString("yyyyMMddHHmmssffff") + fileExtension;
            string fileFullPath = savePath + fileName;

            try
            {
                if (reportViewMain == null)
                {
                    return string.Empty;
                }

                Warning[] warnings;
                string[] strStreamIds;
                string strMimeType;
                string strEncoding;
                string strFileNameExtension;

                byte[] bytes = reportViewMain.LocalReport.Render(fileFormat, null, out strMimeType, out strEncoding, out strFileNameExtension, out strStreamIds, out warnings);

                using (FileStream fs = new FileStream(fileFullPath, FileMode.Create))
                {
                    fs.Write(bytes, 0, bytes.Length);
                    fs.Close();
                }
            }
            catch(Exception ex)
            {
                Exception inner = ex.InnerException;
                string messages = "";
                while (inner != null)
                {
                    messages += inner.Message + ";";
                    inner = inner.InnerException;
                }
                return messages;//string.Empty;
            }

            return fileFullPath;
        }

        private void GetFileFormat(string attachFormat, ref string fileFormat, ref string fileExtension)
        {
            switch (attachFormat)
            {
                case "0":
                    fileFormat = "PDF";
                    break;
                case "1":
                    fileFormat = "Image";
                    break;
                case "2":
                    fileFormat = "Excel";
                    break;
                default:
                    fileFormat = "PDF";
                    break;
            }

            switch (fileFormat)
            {
                case "PDF":
                    fileExtension = ".pdf";
                    break;
                case "Image":
                    fileExtension = ".jpg";
                    break;
                case "Excel":
                    fileExtension = ".xls";
                    break;
                default:
                    fileExtension = ".pdf";
                    break;
            }
        }

        private byte[] GetImageData(string imageFile)
        {
            try
            {
                string imagePath = Request.PhysicalApplicationPath + "Styles\\Images\\" + imageFile;
                FileStream fs = new FileStream(imagePath, FileMode.Open, FileAccess.Read);
                BinaryReader br = new BinaryReader(fs);
                byte[] data = br.ReadBytes((int)br.BaseStream.Length);

                return data;
            }
            catch 
            {
                return null;
            }
        }

        private byte[] SpecimenData
        {
            get
            {
                if (CacheManager.Current.GetData("SpecimenImageData") == null)
                {
                    byte[] data = GetImageData("Specimen.png");

                    if (data != null) CacheManager.Current.Add("SpecimenImageData", data);
                }

                return (byte[])CacheManager.Current.GetData("SpecimenImageData");
            }
        }

        private byte[] VoidData
        {
            get
            {
                if (CacheManager.Current.GetData("VoidImageData") == null)
                {
                    byte[] data = GetImageData("Void.png");
                    CacheManager.Current.Add("VoidImageData", data);
                }

                return (byte[])CacheManager.Current.GetData("VoidImageData");
            }
        }

        //private byte[] FooterData
        //{
        //    get
        //    {
        //        if (CacheManager.Current.GetData("FooterImageData") == null)
        //        {
        //            byte[] data = GetImageData("IATA.png");
        //            CacheManager.Current.Add("FooterImageData", data);
        //        }

        //        return (byte[])CacheManager.Current.GetData("FooterImageData");
        //    }
        //}


        private void ExportForPrint(LocalReport report)
        {
            string deviceInfo =
              "<DeviceInfo>" +
              "  <OutputFormat>EMF</OutputFormat>" +
              "  <PageWidth>8.5in</PageWidth>" +
              "  <PageHeight>11in</PageHeight>" +
              "  <MarginTop>0.25in</MarginTop>" +
              "  <MarginLeft>0.25in</MarginLeft>" +
              "  <MarginRight>0.25in</MarginRight>" +
              "  <MarginBottom>0.25in</MarginBottom>" +
              "</DeviceInfo>";

            Warning[] warnings;
            printStreams = new List<Stream>();
            report.Render("Image", deviceInfo, CreateStream, out warnings);

            foreach (Stream stream in printStreams)
            {
                stream.Position = 0;
            }
        }

        private Stream CreateStream(string name, string fileNameExtension, Encoding encoding, string mimeType, bool willSeek)
        {
            Stream stream = new MemoryStream();
            printStreams.Add(stream);
            return stream;
        }

        private void Print(ref string message)
        {
            if (printStreams == null || printStreams.Count == 0)
            {
                message = "This report no data.";
                return;
            }

            PrintDocument printDoc = new PrintDocument();
            //printDoc.PrinterSettings.PrinterName = "";
            printDoc.DocumentName = "TlEt Report";

            //printDoc.PrinterSettings.PrintToFile = true;

            if (!printDoc.PrinterSettings.IsValid)
            {
                message = "Error:Cannot find the default printer.";
                return;
            }
            printDoc.PrintPage += new PrintPageEventHandler(PrintPage);

            printDoc.Print();
        }

        private void PrintPage(object sender, PrintPageEventArgs ev)
        {
            Metafile pageImage = new Metafile(printStreams[printCurrentPageIndex]);
            ev.Graphics.DrawImage(pageImage, ev.PageBounds);

            printCurrentPageIndex++;
            ev.HasMorePages = (printCurrentPageIndex < printStreams.Count);
        }
        
        public void Dispose()
        {
            if (printStreams != null)
            {
                foreach (Stream stream in printStreams)
                {
                    stream.Close();
                }
                printStreams = null;
            }
        }
    }
}
View Code

 

 

转载于:https://www.cnblogs.com/captainR/p/3302684.html

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
rdlcReport Definition Language Client-Side)是一种用于定义和渲染报表的文件格式,官方提供示例代码来动态生成rdlc报表。 要使用官方示例动态生成rdlc报表,首先需要安装并配置合适的报表生成工具,例如Microsoft Report Viewer控件。然后按照以下步骤进行操作: 1. 创建一个新的C#项目,并打开Visual Studio开发环境。 2. 导入所需的命名空间,包括Microsoft.Reporting.WinForms和System.Data等。 3. 在项目中创建一个新的Windows窗体,可用作报表的展示界面。 4. 在窗体上添加一个ReportViewer控件,作为报表的容器。 5. 在报表的设计视图中,按需求创建报表布局。可以设置报表的标题、列、行、数据源等。 6. 在代码中引入ReportViewer控件,并配置相关属性。 7. 创建报表的数据源,可以使用DataSet、DataTable或直接从数据库中获取数据。 8. 将数据源绑定到报表,并刷新ReportViewer控件以展示数据。 9. 控制报表的显示和打印等功能,例如定义打印布局、页眉和页脚等。 10. 运行程序,即可在ReportViewer中动态生成和展示rdlc报表。 官方示例通常会提供具体的代码和详细的教程,帮助开发者理解和应用rdlc报表的生成过程。通过修改示例代码中的相关参数和数据源,开发者可以根据自己的需求自定义动态生成rdlc报表。 总之,通过官方示例,按照报表设计和生成的步骤,开发者可以利用rdlc动态生成官方示例提供的报表。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值