using Furion; using Furion.FriendlyException; using Furion.JsonSerialization; using Furion.Logging; using Furion.RemoteRequest.Extensions; using Microsoft.Extensions.Logging; using Myshipping.Application.ConfigOption; using Myshipping.Application.Entity; using Myshipping.Application.Enum; using Myshipping.Core; using Newtonsoft.Json.Linq; using NPOI.HPSF; using Org.BouncyCastle.Asn1.X500; using System; using System.Collections.Generic; using System.Collections.Specialized; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; using System.Web; using static System.Net.WebRequestMethods; namespace Myshipping.Application { public static class PrintHelper { /// /// 生成打印文件 /// /// 业务详情JSON /// 请求生成URL /// 数据源Key /// 文档类型 /// 文档模板 /// 返回文件二进制 public static async Task GeneratePrintFile(string busiJson,string reportUrl, string dataSourceKey, PrintFileTypeEnum printFileType, BookingPrintTemplate printTemplate) { var logger = Log.CreateLogger(nameof(PrintHelper)); var opt = App.GetOptions(); var dirAbs = opt.basePath; if (string.IsNullOrEmpty(dirAbs)) { dirAbs = App.WebHostEnvironment.WebRootPath; } //根据部署环境选择替换文件路径 var fileAbsPath = Path.Combine(dirAbs, printTemplate.FilePath); if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { fileAbsPath = fileAbsPath.Replace("\\", "/"); } else { fileAbsPath = fileAbsPath.Replace("/", "\\"); } if (!System.IO.File.Exists(fileAbsPath)) { logger.LogInformation("模板文件不存在 path={path}", fileAbsPath); throw Oops.Bah("模板文件不存在"); } System.IO.FileStream file = new System.IO.FileStream(fileAbsPath, FileMode.Open, FileAccess.Read); int SplitSize = 5242880;//5M分片长度 int index = 1; //序号 第几片 long StartPosition = 5242880 * (index - 1); long lastLens = file.Length - StartPosition;//真不知道怎么起命了,就这样吧 if (lastLens < 5242880) { SplitSize = (int)lastLens; } byte[] heByte = new byte[SplitSize]; file.Seek(StartPosition, SeekOrigin.Begin); //第一个参数是 起始位置 file.Read(heByte, 0, SplitSize); //第三个参数是 读取长度(剩余长度) file.Close(); NameValueCollection par = new NameValueCollection(); par.Add("printType", printFileType.ToString().ToLower()); par.Add($"dataJson{dataSourceKey}", busiJson); var genUrl = $"{reportUrl}Report/PrintReport"; var rtn = TransmitFile(genUrl, par, new { file = "file", fileName = printTemplate.FileName, fileBytes = heByte }); var jobjRtn = JObject.Parse(rtn); logger.LogInformation($"调用报表生成返回:{rtn}"); if (jobjRtn.GetBooleanValue("Success")) { //调用读取文件 var fn = jobjRtn.GetStringValue("Data"); //logger.LogInformation($"准备调用读取报表文件:id:{bookingId},文件名:{fn}"); var readFileUrl = $"{reportUrl}Report/GetFile?fileName={fn}"; var bs = await readFileUrl.GetAsByteArrayAsync(); logger.LogInformation($"调用读取报表文件返回:{bs.Length}"); return bs; } else { throw Oops.Bah($"生成报表文件失败:{jobjRtn.GetStringValue("Message")}"); } } #region 请求打印生成文件 /// /// 请求打印生成文件 /// /// 请求接口地址 /// 键值对参数 /// 文件信息 /// 默认 application/json /// 返回结果 public static string TransmitFile(string requestUrl, NameValueCollection nameValueCollection, dynamic fileInfo, string contentType = "application/json") { var result = string.Empty; using (var httpClient = new HttpClient()) { try { using (var reduceAttach = new MultipartFormDataContent()) { string[] allKeys = nameValueCollection.AllKeys; foreach (string key in allKeys) { var dataContent = new ByteArrayContent(Encoding.UTF8.GetBytes(nameValueCollection[key])); dataContent.Headers.ContentDisposition = new ContentDispositionHeaderValue($"form-data") { Name = key }; reduceAttach.Add(dataContent); } #region 文件参数 if (fileInfo != null) { var Content = new ByteArrayContent(fileInfo.fileBytes); Content.Headers.Add("Content-Type", contentType); reduceAttach.Add(Content, fileInfo.file.ToString(), HttpUtility.UrlEncode(fileInfo.fileName.ToString())); } #endregion //请求 var response = httpClient.PostAsync(requestUrl, reduceAttach).Result; result = response.Content.ReadAsStringAsync().Result; } } catch (Exception ex) { result = JSON.Serialize(new { message = $"{nameof(TransmitFile)} 请求打印生成文件异常,原因:{ex.Message}", status = 0 }); } } return result; } #endregion } }