翼度科技»论坛 编程开发 .net 查看内容

.net core使用Html模板转PDF文件并下载的业务类封装

3

主题

3

帖子

9

积分

新手上路

Rank: 1

积分
9
  前言:我这里文件下载的模板选型优先考虑html模板,上手容易,前后端通用,有了模板后就需要有转换了,html转PDF采用第三方包:SelectPdf,下面是代码核心类:
 
  1-PDFService:
  1. using Microsoft.AspNetCore.Hosting;
  2. using SelectPdf;
  3. namespace MeShop.Domain.PDF
  4. {
  5.     /// <summary>
  6.     /// PDF业务类
  7.     /// </summary>
  8.     public class PDFService
  9.     {
  10.         private readonly IHostingEnvironment hostingEnvironment;
  11.         public PDFService(IHostingEnvironment hostingEnvironment)
  12.         {
  13.             this.hostingEnvironment = hostingEnvironment;
  14.         }
  15.         /// <summary>
  16.         /// 将Html替换参数后转成PDF字节流
  17.         /// </summary>
  18.         /// <param name="htmlFilePath">html模板文件路径</param>
  19.         /// <param name="saveFileName">PDF文件名</param>
  20.         /// <param name="replaceParamDic">变量替换字典</param>
  21.         /// <returns></returns>
  22.         public async Task<string> HtmlToPDFFile(string htmlFilePath, string saveFileName, Dictionary<string, string> replaceParamDic)
  23.         {
  24.             HtmlToPdf Renderer = new HtmlToPdf();
  25.             //设置Pdf参数
  26.             //设置页面方式-横向  PdfPageOrientation.Portrait  竖向
  27.             Renderer.Options.PdfPageOrientation = PdfPageOrientation.Landscape;
  28.             //设置页面大小,30种页面大小可以选择
  29.             Renderer.Options.PdfPageSize = PdfPageSize.A4;
  30.             //上下左右边距设置  
  31.             Renderer.Options.MarginTop = 10;
  32.             Renderer.Options.MarginBottom = 10;
  33.             Renderer.Options.MarginLeft = 10;
  34.             Renderer.Options.MarginRight = 10;
  35.             //设置更多额参数可以去HtmlToPdfOptions里面选择设置
  36.             //根据html内容导出PDF
  37.             string docHtml = await File.ReadAllTextAsync(htmlFilePath, Encoding.UTF8);
  38.             foreach (var item in replaceParamDic)
  39.             {
  40.                 docHtml = docHtml.Replace(item.Key, item.Value);
  41.             }
  42.             PdfDocument pdfDocument = Renderer.ConvertHtmlString(docHtml);
  43.             string saveFilePath = @$"{this.hostingEnvironment.ContentRootPath}\staticfiles\Download\{saveFileName}";
  44.             if (File.Exists(saveFilePath))
  45.             {
  46.                 File.Delete(saveFilePath);
  47.             }
  48.             pdfDocument.Save(saveFilePath);
  49.             return saveFilePath;
  50.         }
  51.         /// <summary>
  52.         /// 读取文件字节流
  53.         /// </summary>
  54.         /// <param name="filePath">资源文件(包含路径)</param>
  55.         /// <param name="isDeleteSourceFile">是否删除资源文件</param>
  56.         /// <returns></returns>
  57.         public async Task<byte[]> GetByteByFile(string? filePath, bool isDeleteSourceFile = false)
  58.         {
  59.             byte[]? myByteArray = null;
  60.             if (filePath != null && File.Exists(filePath))
  61.             {
  62.                 using (FileStream fileStream = new FileStream(filePath, FileMode.Open))
  63.                 {
  64.                     fileStream.Seek(0, SeekOrigin.Begin);
  65.                     myByteArray = new byte[fileStream.Length];
  66.                     await fileStream.ReadAsync(myByteArray, 0, (int)fileStream.Length);
  67.                 }
  68.                 if (isDeleteSourceFile)
  69.                 {
  70.                     File.Delete(filePath);
  71.                 }
  72.             }
  73.             return myByteArray ?? new byte[0];
  74.         }
  75.         /// <summary>
  76.         /// 压缩多个文件为zip文件
  77.         /// </summary>
  78.         /// <param name="zipFileName">zip压缩文件名</param>
  79.         /// <param name="filePaths">资源文件列表(包含路径)</param>
  80.         /// <param name="isDeleteSourceFile">是否删除资源文件</param>
  81.         /// <returns></returns>
  82.         public string CompressFileToZip(string zipFileName, string[] filePaths, bool isDeleteSourceFile = false)
  83.         {
  84.             string? zipFilePath = null;
  85.             if (!string.IsNullOrWhiteSpace(zipFileName) && filePaths.Length > 0)
  86.             {
  87.                 string zipDirectoryPath = @$"{this.hostingEnvironment.ContentRootPath}\staticfiles\Download\{DateTime.Now.ToString("yyyyMMddHHmmssfff")}";
  88.                 if (!Directory.Exists(zipDirectoryPath))
  89.                 {
  90.                     Directory.CreateDirectory(zipDirectoryPath);
  91.                 }
  92.                 zipFilePath = @$"{this.hostingEnvironment.ContentRootPath}\staticfiles\Download\{zipFileName}";
  93.                 if (File.Exists(zipFilePath))
  94.                 {
  95.                     File.Delete(zipFilePath);
  96.                 }
  97.                 foreach (var filePath in filePaths)
  98.                 {
  99.                     string? fileName = filePath.Split('\\').LastOrDefault();
  100.                     string copyFilePath = @$"{zipDirectoryPath}\{fileName}";
  101.                     if (isDeleteSourceFile)
  102.                     {
  103.                         File.Move(filePath, copyFilePath);
  104.                     }
  105.                     else
  106.                     {
  107.                         File.Copy(filePath, copyFilePath);
  108.                     }
  109.                 }
  110.                 CompressionHelper.Compression(zipDirectoryPath, zipFilePath);
  111.                 //压缩完成后,删除压缩使用文件夹及其子项
  112.                 Directory.Delete(zipDirectoryPath, true);
  113.             }
  114.             return zipFilePath ?? "";
  115.         }
  116.     }
  117. }
复制代码
   2-控制器方法示例:
  1. [HttpGet("DownloadSettlement")]
  2. public async Task<JsonModel<byte[]>> DownloadSettlement(string settlementIDS)
  3. {
  4.     byte[]? byteArray = null;
  5.     string[] settlementIDArray = settlementIDS.Split(',');
  6.     string templateHtmlPath = @$"{this.hostingEnvironment.ContentRootPath}\staticfiles\agentusersettlement.html";
  7.     List<string> zipSaveFilePathList = new List<string>(settlementIDArray.Length);
  8.     Base_shop baseShop = await this.shopService.GetBaseShopAsync();
  9.     foreach (var item in settlementIDArray)
  10.     {
  11.         long settlementID = TypeParseHelper.StrToInt64(item);
  12.         ResponseAgentUserSettlementDetail? detail = await this.agentUserSettlementService.GetDetailAsync(settlementID);
  13.         if (detail != null)
  14.         {
  15.             Agent_user agentUser = await this.agentUserService.GetAsync(detail.AgentUserID) ?? new Agent_user();
  16.             Dictionary<string, string> replaceDic = new Dictionary<string, string>()
  17.             {
  18.                 {"@InvoiceNumber@",$"{detail.UpdateTime.ToString("yyyyMMdd")}{detail.ID}" },
  19.                 {"@UpdateTime@",$"{detail.UpdateTime.ToString("yyyyMMdd")}" },
  20.                 {"@AgentUserCompanyName@",$"{agentUser.CompanyName}" },
  21.                 {"@AgentUserCompanyAddress@",$"{agentUser.CompanyAddress}" },
  22.                 {"@BeginDate@",$"{detail.BeginDate.ToString("yyyy/MM/dd")}" },
  23.                 {"@EndDate@",$"{detail.EndDate.ToString("yyyy/MM/dd")}" },
  24.                 {"@TotalPoint@",$"{detail.TotalPoint.ToString("F3")}" },
  25.                 {"@AccountCompanyName@",$"{baseShop.CompanyName}" },
  26.                 {"@AccountCompanyAddress@",$"{baseShop.CompanyAddress}" },
  27.                 {"@AccountEmail@",$"{baseShop.ServiceEmail}" }
  28.             };
  29.             zipSaveFilePathList.Add(await this.pdfService.HtmlToPDFFile(templateHtmlPath, $"{settlementID}.pdf", replaceDic));
  30.             //设置导出状态
  31.             await this.agentUserSettlementService.SetExportStateAsync(settlementID, (int)EState.启用);
  32.         }
  33.     }
  34.     if (zipSaveFilePathList.Count == 1)
  35.     {
  36.         byteArray = await this.pdfService.GetByteByFile(zipSaveFilePathList.FirstOrDefault());
  37.     }
  38.     else
  39.     {
  40.         string zipFilePath = this.pdfService.CompressFileToZip($"{settlementIDS.Replace(',', '_')}.zip", zipSaveFilePathList.ToArray(), true);
  41.         byteArray = await this.pdfService.GetByteByFile(zipFilePath);
  42.     }
  43.     return base.SuccessResult(byteArray ?? new byte[0]);
  44. }
复制代码
 
  3-前台JS下载文件字节流示例:
[code][/code] 
 
 
来源:https://www.cnblogs.com/lxhbky/archive/2023/06/16/17486147.html
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!

举报 回复 使用道具