WordHelperService.cs 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. using Hotline.Share.Dtos.ExportWord;
  2. using XF.Domain.Dependency;
  3. namespace Hotline.Application.ExportWord
  4. {
  5. public class WordHelperService : IWordHelperService, IScopeDependency
  6. {
  7. public byte[] WordByte<T>(string templatePath, T data) where T : IWordExportTemplate
  8. {
  9. return new WordExportService(new WordExportProvider()).TemplateCreateWord(templatePath, data).WordBytes;
  10. }
  11. public Stream WordStream<T>(string templatePath, T data) where T : IWordExportTemplate
  12. {
  13. var bytes = new WordExportService(new WordExportProvider()).TemplateCreateWord(templatePath, data).WordBytes;
  14. Stream stream = new MemoryStream(bytes);
  15. return stream;
  16. }
  17. /// <summary>
  18. /// ZipStream 压缩
  19. /// </summary>
  20. /// <param name="streams">Dictionary(string, Stream) 文件名和Stream</param>
  21. /// <returns></returns>
  22. public byte[] ConvertZipStream(Dictionary<string, Stream> streams)
  23. {
  24. byte[] buffer = new byte[6500];
  25. MemoryStream returnStream = new();
  26. var zipMs = new MemoryStream();
  27. using (ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipStream = new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(zipMs))
  28. {
  29. zipStream.SetLevel(9);//设置 压缩等级 (9级 500KB 压缩成了96KB)
  30. foreach (var kv in streams)
  31. {
  32. string fileName = kv.Key;
  33. using (var streamInput = kv.Value)
  34. {
  35. ICSharpCode.SharpZipLib.Zip.ZipEntry zipEntry = new ICSharpCode.SharpZipLib.Zip.ZipEntry(fileName);
  36. zipEntry.IsUnicodeText = true;
  37. zipStream.PutNextEntry(zipEntry);
  38. while (true)
  39. {
  40. var readCount = streamInput.Read(buffer, 0, buffer.Length);
  41. if (readCount > 0)
  42. {
  43. zipStream.Write(buffer, 0, readCount);
  44. }
  45. else
  46. {
  47. break;
  48. }
  49. }
  50. zipStream.Flush();
  51. }
  52. }
  53. zipStream.Finish();
  54. zipMs.Position = 0;
  55. zipMs.CopyTo(returnStream, 5600);
  56. }
  57. returnStream.Position = 0;
  58. //Stream转Byte[]
  59. byte[] returnBytes = new byte[returnStream.Length];
  60. returnStream.Read(returnBytes, 0, returnBytes.Length);
  61. returnStream.Seek(0, SeekOrigin.Begin);
  62. return returnBytes;
  63. }
  64. }
  65. }