using FastReport; using FastReport.Export.Pdf; using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Text; using System.Timers; using System.Web; namespace BLL { public static class FastReportService { private static Timer tempReportCleanupTimer; /// /// 重置数据 /// public static void ResetData() { HttpContext.Current.Session["ReportDataTables"] = null; HttpContext.Current.Session["ReportParameterValues"] = null; } public static void AddFastreportTable(DataTable dataTable) { List dataTables = (List)HttpContext.Current.Session["ReportDataTables"]; if (dataTables == null) { dataTables = new List(); } dataTables.Add(dataTable); HttpContext.Current.Session["ReportDataTables"] = dataTables; } public static void AddFastreportParameter(Dictionary Dicparames) { HttpContext.Current.Session["ReportParameterValues"] = Dicparames; } /// /// 启动临时报表清理定时器,定期删除超过 1 小时的 PDF。 /// public static void StartTempReportCleanupMonitor() { if (tempReportCleanupTimer != null) { tempReportCleanupTimer.Stop(); tempReportCleanupTimer.Dispose(); tempReportCleanupTimer = null; } CleanExpiredTempReports(); tempReportCleanupTimer = new Timer { AutoReset = true, Interval = 1000 * 60 * 30 }; tempReportCleanupTimer.Elapsed += TempReportCleanupTimer_Elapsed; tempReportCleanupTimer.Start(); } private static void TempReportCleanupTimer_Elapsed(object sender, ElapsedEventArgs e) { CleanExpiredTempReports(); } /// /// 删除 File/Fastreport/Temp 下创建时间超过 1 小时的 PDF 临时文件。 /// public static void CleanExpiredTempReports() { try { string tempDirectory = Path.Combine(Funs.RootPath, @"File\Fastreport\Temp\"); if (!Directory.Exists(tempDirectory)) { return; } DateTime expiredTime = DateTime.Now.AddHours(-1); foreach (string file in Directory.GetFiles(tempDirectory, "*.pdf", SearchOption.TopDirectoryOnly)) { FileInfo fileInfo = new FileInfo(file); if (fileInfo.CreationTime < expiredTime) { fileInfo.Attributes = FileAttributes.Normal; fileInfo.Delete(); } } } catch (Exception ex) { ErrLogInfo.WriteLog(ex, "FastReport临时报表清理", "FastReportService.CleanExpiredTempReports"); } } /// /// 导出报表 PDF 到临时目录,并返回可访问的相对 URL。 /// /// 报表模板路径,支持绝对路径或相对 Funs.RootPath 的路径。 public static string ExportReport(string reportPath) { List dataTables = (List)HttpContext.Current.Session["ReportDataTables"]; Dictionary parameterValues = (Dictionary)HttpContext.Current.Session["ReportParameterValues"]; return ExportReport(reportPath, dataTables, parameterValues); } /// /// 导出报表 PDF 到临时目录,并返回可访问的相对 URL。 /// /// 报表模板路径,支持绝对路径或相对 Funs.RootPath 的路径。 /// 报表数据源集合。 /// 报表参数集合。 public static string ExportReport(string reportPath, List dataTables, Dictionary parameterValues) { string fullReportPath = GetReportFullPath(reportPath); if (string.IsNullOrEmpty(fullReportPath) || !File.Exists(fullReportPath)) { throw new FileNotFoundException("打印模板不存在!", reportPath); } string relativeDirectory = @"File\Fastreport\Temp\"; string tempDirectory = Path.Combine(Funs.RootPath, relativeDirectory); if (!Directory.Exists(tempDirectory)) { Directory.CreateDirectory(tempDirectory); } string fileName = "report_" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + "_" + Guid.NewGuid().ToString("N") + ".pdf"; string filePath = Path.Combine(tempDirectory, fileName); using (Report report = BuildPreparedReport(fullReportPath, dataTables, parameterValues)) using (PDFExport pdfExport = new PDFExport()) { // Web 打印先导出 PDF,前端用 iframe 装载后调用浏览器打印。 pdfExport.PrintScaling = false; pdfExport.ShowPrintDialog = true; report.Export(pdfExport, filePath); } return "~/" + relativeDirectory.Replace("\\", "/") + fileName; } private static Report BuildPreparedReport(string reportPath, List dataTables, Dictionary parameterValues) { FastReport.Utils.Config.WebMode = true; Report report = new Report(); report.Load(reportPath); if (report.Dictionary.Connections.Count > 0) { var reportConnection = report.Dictionary.Connections[0]; if (reportConnection.ConnectionString != Funs.ConnString) { // 打印时只替换本次报表连接,避免把运行环境连接串写回模板文件。 reportConnection.ConnectionString = Funs.ConnString; } } if (dataTables != null && dataTables.Count > 0) { for (int i = 0; i < dataTables.Count; i++) { report.RegisterData(dataTables[i], dataTables[i].TableName); } } if (parameterValues != null && parameterValues.Count > 0) { foreach (KeyValuePair kvp in parameterValues) { report.SetParameterValue(kvp.Key, kvp.Value); } } report.Prepare(); return report; } private static string GetReportFullPath(string reportPath) { if (string.IsNullOrEmpty(reportPath)) { return reportPath; } if (Path.IsPathRooted(reportPath)) { return reportPath; } return Path.Combine(Funs.RootPath, reportPath.TrimStart('\\', '/')); } /// /// 合并报表后打印 /// /// 报表实体集 /// 导出的路径 public static void ExportMergeReport(List fastReportItems, string path, string printType) { Report report = new Report(); report.PrintSettings.ShowDialog = false; //隐藏弹窗 FastReport.EnvironmentSettings settings = new EnvironmentSettings(); settings.ReportSettings.ShowProgress = false; //隐藏进度条 for (int i = 0; i < fastReportItems.Count; i++) { report.Load(Funs.RootPath + fastReportItems[i].ReportPath); //加载报表 List dataTables = fastReportItems[i].DataTables; Dictionary ParameterValues = fastReportItems[i].ParameterValues; if (dataTables != null && dataTables.Count > 0) { for (int j = 0; j < dataTables.Count; j++) { report.RegisterData(dataTables[j], dataTables[j].TableName);//绑定数据源 } } if (ParameterValues.Count > 0) { foreach (KeyValuePair kvp in ParameterValues) { report.SetParameterValue(kvp.Key, kvp.Value);//绑定参数 } } if (i == 0) { report.Prepare(); } else { report.Prepare(true); } } if (printType == "1") { FastReport.Export.Pdf.PDFExport exp = new FastReport.Export.Pdf.PDFExport(); report.Export(exp, path); } else if (printType == "2") { FastReport.Export.OoXML.Word2007Export exportBase = new FastReport.Export.OoXML.Word2007Export(); report.Export(export: exportBase, fileName: path.Replace(oldValue: "pdf", newValue: "docx")); } } } }