Files
SGGL_SHJ/SGGL/BLL/Common/FastReport.cs
T
2026-06-24 09:59:56 +08:00

250 lines
9.5 KiB
C#

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;
/// <summary>
/// 重置数据
/// </summary>
public static void ResetData()
{
HttpContext.Current.Session["ReportDataTables"] = null;
HttpContext.Current.Session["ReportParameterValues"] = null;
}
public static void AddFastreportTable(DataTable dataTable)
{
List<DataTable> dataTables = (List<DataTable>)HttpContext.Current.Session["ReportDataTables"];
if (dataTables == null)
{
dataTables = new List<DataTable>();
}
dataTables.Add(dataTable);
HttpContext.Current.Session["ReportDataTables"] = dataTables;
}
public static void AddFastreportParameter(Dictionary<string, string> Dicparames)
{
HttpContext.Current.Session["ReportParameterValues"] = Dicparames;
}
/// <summary>
/// 启动临时报表清理定时器,定期删除超过 1 小时的 PDF。
/// </summary>
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();
}
/// <summary>
/// 删除 File/Fastreport/Temp 下创建时间超过 1 小时的 PDF 临时文件。
/// </summary>
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");
}
}
/// <summary>
/// 导出报表 PDF 到临时目录,并返回可访问的相对 URL。
/// </summary>
/// <param name="reportPath">报表模板路径,支持绝对路径或相对 Funs.RootPath 的路径。</param>
public static string ExportReport(string reportPath)
{
List<DataTable> dataTables = (List<DataTable>)HttpContext.Current.Session["ReportDataTables"];
Dictionary<string, string> parameterValues = (Dictionary<string, string>)HttpContext.Current.Session["ReportParameterValues"];
return ExportReport(reportPath, dataTables, parameterValues);
}
/// <summary>
/// 导出报表 PDF 到临时目录,并返回可访问的相对 URL。
/// </summary>
/// <param name="reportPath">报表模板路径,支持绝对路径或相对 Funs.RootPath 的路径。</param>
/// <param name="dataTables">报表数据源集合。</param>
/// <param name="parameterValues">报表参数集合。</param>
public static string ExportReport(string reportPath, List<DataTable> dataTables, Dictionary<string, string> 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<DataTable> dataTables, Dictionary<string, string> 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<string, string> 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('\\', '/'));
}
/// <summary>
/// 合并报表后打印
/// </summary>
/// <param name="fastReportItems">报表实体集</param>
/// <param name="path">导出的路径</param>
public static void ExportMergeReport(List<Model.FastReportItem> 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<DataTable> dataTables = fastReportItems[i].DataTables;
Dictionary<string, string> 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<string, string> 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"));
}
}
}
}