FlowService.Actions3.Others.cs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Threading.Tasks;
  6. using DocumentFormat.OpenXml.Drawing;
  7. using DocumentFormat.OpenXml.Packaging;
  8. using GxPress.Common.Tools;
  9. namespace GxPress.Service.Implement
  10. {
  11. public partial class FlowService
  12. {
  13. public async Task<string> DownloadAsync(int flowId)
  14. {
  15. var flow = await _flowRepository.GetAsync(flowId);
  16. var process = await _processRepository.GetAsync(flow.ProcessId);
  17. var rootPath = StringUtils.GetWebRootPath(_environment.WebRootPath);
  18. var path = System.IO.Path.Combine(rootPath, StringUtils.RemoveDomain(process.TemplatePath));
  19. if (!File.Exists(path))
  20. {
  21. return $"/template.docx";
  22. }
  23. var saveDirectory = DateTime.Now.ToString("yyyyMMdd");
  24. var absolutePath = System.IO.Path.Combine(rootPath, "cache", saveDirectory, $"{process.Name}.docx");
  25. var relativePath = $"/cache/{saveDirectory}/{process.Name}.docx";
  26. var fieldList = await _processFieldRepository.GetListAsync(flow.ProcessId);
  27. var valueList = await _flowFieldValueRepository.GetListAsync(flowId);
  28. var nameValueList = new List<KeyValuePair<string, string>>();
  29. if (fieldList != null)
  30. {
  31. foreach (var processField in fieldList)
  32. {
  33. var value = valueList?.FirstOrDefault(v => v.FieldId == processField.Id);
  34. if (value != null)
  35. {
  36. nameValueList.Add(new KeyValuePair<string, string>(processField.Label, GetFieldValue(value)));
  37. }
  38. }
  39. }
  40. using (var doc = WordprocessingDocument.Open(path, true))
  41. {
  42. var body = doc.MainDocumentPart.Document.Body;
  43. var paras = body.Elements<Paragraph>();
  44. foreach (var para in paras)
  45. {
  46. foreach (var run in para.Elements<Run>())
  47. {
  48. foreach (var text in run.Elements<Text>())
  49. {
  50. foreach (var pair in nameValueList)
  51. {
  52. text.Text = text.Text.Replace($"[{pair.Key}]", pair.Value);
  53. }
  54. }
  55. }
  56. }
  57. doc.SaveAs(absolutePath);
  58. }
  59. return relativePath;
  60. }
  61. }
  62. }