using DS.WMS.PrintApi.Model; using DS.WMS.PrintApi.Utils; using FastReport.Data.JsonConnection; using FastReport.Export.OoXML; using FastReport.Export.Pdf; using System.IO; using System.Text; using System; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc.Rendering; using SqlSugar; using static System.Net.Mime.MediaTypeNames; using System.Collections.Generic; using Newtonsoft.Json; using Microsoft.Extensions.DependencyInjection; using DS.WMS.PrintApi.Middleware; using Newtonsoft.Json.Schema; namespace DS.WMS.PrintApi.Service { public class OpenPrintService : IOpenPrintService { private readonly IServiceProvider _serviceProvider; private readonly ISqlSugarClient db; private readonly ISaasDbService saasService; /// /// /// /// public OpenPrintService(IServiceProvider serviceProvider) { _serviceProvider = serviceProvider; db = _serviceProvider.GetRequiredService(); saasService = _serviceProvider.GetRequiredService(); } public async Task GetOpenJsonPrintInfo(OpenJsonPrintReq req) { try { var template = db.Queryable().Filter(null, true).Where(x => x.Id == req.TemplateId).First(); if (template == null) { return await Task.FromResult(PrintDataResult.Failed("打印模板不存在!")); } if (template.IsUseDataSource) { return await Task.FromResult(PrintDataResult.Failed("非Json打印接口!")); } if (String.IsNullOrEmpty(template.PrintJsonContent)) { return await Task.FromResult(PrintDataResult.Failed("打印模板内容不能为空!")); } try { var basePath = String.Empty; var savePath = "wwwroot/PrintTempFile"; var fileName = DateTime.Now.Ticks + "-" + NumUtil.GetRandomString(3); var printFileName = $"{fileName}.frx"; var printFile = Path.Combine(savePath, printFileName); //写入CRX文件 using (FileStream fs = new FileStream(printFile, FileMode.Create)) { Byte[] info = new UTF8Encoding(true).GetBytes(template.PrintJsonContent); fs.Write(info, 0, info.Length); } //生成报表 FastReport.Report report = new FastReport.Report(); report.Load(printFile); //var dataSource = report.Dictionary.Connections[0] as JsonDataSourceConnection; //var str = new FastReport.Data.JsonConnection.JsonDataSourceConnectionStringBuilder(); //str.Json = req.JsonDataStr; //dataSource.ConnectionString = str.ConnectionString; //var str = new FastReport.Data.JsonConnection.JsonDataSourceConnectionStringBuilder(); //str.Json = req.JsonDataStr; //str.JsonSchema.InitSchema(); //report.Dictionary.Connections.Clear(); if (report.Dictionary.Connections.Count == 0) { //重置数据源 report.Dictionary.Connections.Add(new JsonDataSourceConnection() { ConnectionString = $"JSON={req.JsonDataStr};Encoding=utf-8", Name = "Connection", }); } else { var dataSource = report.Dictionary.Connections[0] as JsonDataSourceConnection; dataSource.Name = "Connection"; dataSource.ConnectionString = $"JSON={req.JsonDataStr};Encoding=utf-8"; } report.Save(printFile); report.Prepare(); var printName = string.Empty; var saveFile = string.Empty; //var saveFile = Path.Combine(savePath, printName); if (req.PrintType == "1") { printName = $"{fileName}.pdf"; saveFile = Path.Combine(savePath, printName); PDFExport pdfExport = new PDFExport(); pdfExport.Export(report, saveFile); } else if (req.PrintType == "2") { printName = $"{fileName}.xlsx"; saveFile = Path.Combine(savePath, printName); Excel2007Export excelExport = new Excel2007Export(); excelExport.Export(report, saveFile); } else if (req.PrintType == "3") { printName = $"{fileName}.doc"; saveFile = Path.Combine(savePath, printName); Word2007Export wordExport = new Word2007Export(); wordExport.Export(report, saveFile); } else { return await Task.FromResult(PrintDataResult.Failed("非法打印格式!")); } return await Task.FromResult(PrintDataResult.OK(printName)); } catch (Exception e) { return await Task.FromResult(PrintDataResult.Failed(e.Message)); } } catch (Exception ex) { //Logger.Warn(ex, "方法: GetOpenJsonPrintInfo"); return await Task.FromResult(PrintDataResult.Failed(ex.Message)); } } public async Task GetOpenJsonPrintInfoByTemplateCode(OpenJsonPrintByCodeReq req) { try { var template = db.Queryable().Filter(null, true).Where(x => x.TemplateCode == req.Code && x.TenantId == req.TenantId).First(); if (template == null) { return await Task.FromResult(PrintDataResult.Failed("打印模板编码:[" + req.Code + "]的打印格式不存在!")); } if (template.IsUseDataSource) { return await Task.FromResult(PrintDataResult.Failed("非Json打印接口!")); } if (String.IsNullOrEmpty(template.PrintJsonContent)) { return await Task.FromResult(PrintDataResult.Failed("打印模板内容不能为空!")); } try { var basePath = String.Empty; var savePath = "wwwroot/PrintTempFile"; var fileName = DateTime.Now.Ticks + "-" + NumUtil.GetRandomString(3); var printFileName = $"{fileName}.frx"; var printFile = Path.Combine(savePath, printFileName); //写入CRX文件 using (FileStream fs = new FileStream(printFile, FileMode.Create)) { Byte[] info = new UTF8Encoding(true).GetBytes(template.PrintJsonContent); fs.Write(info, 0, info.Length); } //生成报表 FastReport.Report report = new FastReport.Report(); report.Load(printFile); //var dataSource = report.Dictionary.Connections[0] as JsonDataSourceConnection; //var str = new FastReport.Data.JsonConnection.JsonDataSourceConnectionStringBuilder(); //str.Json = req.JsonDataStr; //dataSource.ConnectionString = str.ConnectionString; var str = new FastReport.Data.JsonConnection.JsonDataSourceConnectionStringBuilder(); str.Json = req.JsonDataStr; //if (report.Dictionary.Connections.Count == 0) //{ // //重置数据源 // report.Dictionary.Connections.Add(new JsonDataSourceConnection() // { // ConnectionString = str.ConnectionString, // Name = "Connection", // }); //} //else //{ // var dataSource = report.Dictionary.Connections[0] as JsonDataSourceConnection; // dataSource.Name = "Connection"; // dataSource.ConnectionString = str.ConnectionString; //} if (report.Dictionary.Connections.Count == 0) { //重置数据源 report.Dictionary.Connections.Add(new JsonDataSourceConnection() { ConnectionString = $"JSON={req.JsonDataStr};Encoding=utf-8", Name = "Connection", }); } else { var dataSource = report.Dictionary.Connections[0] as JsonDataSourceConnection; dataSource.Name = "Connection"; dataSource.ConnectionString = $"JSON={req.JsonDataStr};Encoding=utf-8"; } report.Save(printFile); report.Save(printFile); report.Prepare(); var printName = string.Empty; var saveFile = string.Empty; //var saveFile = Path.Combine(savePath, printName); if (req.PrintType == "1") { printName = $"{fileName}.pdf"; saveFile = Path.Combine(savePath, printName); PDFExport pdfExport = new PDFExport(); pdfExport.Export(report, saveFile); #region 处理托书挂载附件 if (template.TemplateCode == "bill_of_lading") { System.IO.FileStream file = new System.IO.FileStream(saveFile, FileMode.Open, FileAccess.Read); var movePath = Path.Combine(AppSetting.Configuration["FileSettings:MovePath"], printName); using (var fileStream = File.Create(movePath)) { await file.CopyToAsync(fileStream); } file.Close(); } #endregion } else if (req.PrintType == "2") { printName = $"{fileName}.xlsx"; saveFile = Path.Combine(savePath, printName); Excel2007Export excelExport = new Excel2007Export(); excelExport.Export(report, saveFile); } else if (req.PrintType == "3") { printName = $"{fileName}.doc"; saveFile = Path.Combine(savePath, printName); Word2007Export wordExport = new Word2007Export(); wordExport.Export(report, saveFile); } else { return await Task.FromResult(PrintDataResult.Failed("非法打印格式!")); } return await Task.FromResult(PrintDataResult.OK(printName)); } catch (Exception e) { return await Task.FromResult(PrintDataResult.Failed(e.Message)); } } catch (Exception ex) { //Logger.Warn(ex, "方法: GetOpenJsonPrintInfo"); return await Task.FromResult(PrintDataResult.Failed(ex.Message)); } } /// /// sql 打印 /// /// /// public async Task GetOpenSqlPrintInfo(OpenSqlPrintReq req) { try { if (req.TenantId == 0 || req.TenantId == null) { return await Task.FromResult(PrintDataResult.Failed("缺失关键参数租户id!")); } var template = await db.Queryable().Filter(null, true).Where(x => x.TenantId == req.TenantId) .WhereIF(req.TemplateId != 0, x => x.Id == req.TemplateId) .WhereIF(!string.IsNullOrEmpty(req.TemplateCode), x => x.Id == req.TemplateId) .FirstAsync(); if (template == null) { return await Task.FromResult(PrintDataResult.Failed("打印模板不存在!")); } if (!template.IsUseDataSource) { return await Task.FromResult(PrintDataResult.Failed("非Sql打印接口!")); } if (string.IsNullOrEmpty(template.SourceSql)) { return await Task.FromResult(PrintDataResult.Failed("打印数据源不能为空!")); } if (!template.SourceSql.Contains(';')) { return await Task.FromResult(PrintDataResult.Failed("数据源必须包含分号!")); } if (template.SourceSql.Substring(template.SourceSql.Length - 1, 1) != ";") { return await Task.FromResult(PrintDataResult.Failed("数据源最后必须包含分号!")); } if (SqlUtil.IsSqlInjection(template.SourceSql)) { return await Task.FromResult(PrintDataResult.Failed("sql数据源包含非法字符,请检查!")); } if (String.IsNullOrEmpty(template.PrintJsonContent)) { return await Task.FromResult(PrintDataResult.Failed("打印模板内容不能为空!")); } try { var tenantDb = saasService.GetBizDbScopeById(req.TenantId); var data = new Dictionary>(); var sugarParams = new List(); if (!string.IsNullOrEmpty(req.ParamJsonStr)) { var param = JsonHelper.Instance.Deserialize>(req.ParamJsonStr); foreach (var p in param) { sugarParams.Add(new SugarParameter($"@{p.Key}", p.Value)); } } if (template.SourceSql.Contains(';')) { var sqlArr = template.SourceSql.Split(';'); if (sqlArr.Length > 0) { for (int i = 0; i < sqlArr.Length; i++) { if (!string.IsNullOrEmpty(sqlArr[i])) { var temp = tenantDb.Ado.SqlQuery(sqlArr[i], sugarParams); data.Add("sql" + i, temp); } } } else { } } var basePath = String.Empty; var savePath = "wwwroot/PrintTempFile"; var fileName = DateTime.Now.Ticks + "-" + NumUtil.GetRandomString(3); var printFileName = $"{fileName}.frx"; var printFile = Path.Combine(savePath, printFileName); //写入CRX文件 using (FileStream fs = new FileStream(printFile, FileMode.Create)) { Byte[] info = new UTF8Encoding(true).GetBytes(template.PrintJsonContent); fs.Write(info, 0, info.Length); } //生成报表 FastReport.Report report = new FastReport.Report(); report.Load(printFile); var str = new FastReport.Data.JsonConnection.JsonDataSourceConnectionStringBuilder(); str.Json = JsonConvert.SerializeObject(data); //if (report.Dictionary.Connections.Count == 0) //{ // //重置数据源 // report.Dictionary.Connections.Add(new JsonDataSourceConnection() // { // ConnectionString = str.ConnectionString, // Name = "Connection", // }); //} //else { // var dataSource = report.Dictionary.Connections[0] as JsonDataSourceConnection; // dataSource.Name = "Connection"; // dataSource.ConnectionString = str.ConnectionString; //} if (report.Dictionary.Connections.Count == 0) { //重置数据源 report.Dictionary.Connections.Add(new JsonDataSourceConnection() { ConnectionString = $"JSON={JsonConvert.SerializeObject(data)};Encoding=utf-8", Name = "Connection", }); } else { var dataSource = report.Dictionary.Connections[0] as JsonDataSourceConnection; dataSource.Name = "Connection"; dataSource.ConnectionString = $"JSON={JsonConvert.SerializeObject(data)};Encoding=utf-8"; } report.Save(printFile); report.Prepare(); var printName = string.Empty; var saveFile = string.Empty; //var saveFile = Path.Combine(savePath, printName); if (req.PrintType == "1") { printName = $"{fileName}.pdf"; saveFile = Path.Combine(savePath, printName); PDFExport pdfExport = new PDFExport(); pdfExport.Export(report, saveFile); } else if (req.PrintType == "2") { printName = $"{fileName}.xlsx"; saveFile = Path.Combine(savePath, printName); Excel2007Export excelExport = new Excel2007Export(); excelExport.Export(report, saveFile); } else if (req.PrintType == "3") { printName = $"{fileName}.doc"; saveFile = Path.Combine(savePath, printName); Word2007Export wordExport = new Word2007Export(); wordExport.Export(report, saveFile); } else { return await Task.FromResult(PrintDataResult.Failed("非法打印格式!")); } return await Task.FromResult(PrintDataResult.OK(printName)); } catch (Exception e) { return await Task.FromResult(PrintDataResult.Failed(e.Message)); } } catch (Exception ex) { //Logger.Warn(ex, "方法: GetOpenJsonPrintInfo"); return await Task.FromResult(PrintDataResult.Failed(ex.Message)); } } } }