CompareDocx.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Text;
  5. using DiffPlex;
  6. using System.IO.Packaging;
  7. using System.Text.RegularExpressions;
  8. using System.Linq;
  9. using Microsoft.Office.Interop.Word;
  10. using wispro.sp.entity.CompareCase;
  11. namespace wispro.sp.utility
  12. {
  13. /// <summary>
  14. /// 比较两个Docx文档中文字的不同
  15. /// </summary>
  16. public class CompareDocx
  17. {
  18. public class PatentDocument
  19. {
  20. public string FilePath { get; set; }
  21. public string Abstract { get; set; }
  22. public string Claim { get; set; }
  23. public string FullText { get; set; }
  24. public string DocumentString { get; set; }
  25. public PatentDocument(string filePath) {
  26. this.FilePath = filePath;
  27. if (!System.IO.File.Exists(this.FilePath) )
  28. {
  29. throw new ApplicationException("指定的文件不存在!");
  30. }
  31. if (this.FilePath.EndsWith(".doc"))
  32. {
  33. DocumentString = GetDocTxt(this.FilePath);
  34. }
  35. else
  36. {
  37. DocumentString = GetDocxTxt(this.FilePath);
  38. }
  39. }
  40. private string GetDocTxt(string filePath)
  41. {
  42. Application word = null;
  43. Document doc = null;
  44. string content = string.Empty;
  45. try
  46. {
  47. // 创建Word应用实例
  48. word = new Application();
  49. // 打开Word文档
  50. System.IO.FileInfo fileInfo = new System.IO.FileInfo(filePath);
  51. doc = word.Documents.Open(fileInfo.FullName);
  52. // 读取文档内容
  53. content = doc.Content.Text;
  54. List<string> lines = content.Split("\r").ToList();
  55. return List2String(lines);
  56. }
  57. catch (Exception ex)
  58. {
  59. throw new Exception($"读取Word文档时发生错误: {ex.Message}");
  60. }
  61. finally
  62. {
  63. // 关闭文档
  64. if (doc != null)
  65. {
  66. doc.Close();
  67. #pragma warning disable CA1416 // 验证平台兼容性
  68. System.Runtime.InteropServices.Marshal.ReleaseComObject(doc);
  69. #pragma warning restore CA1416 // 验证平台兼容性
  70. }
  71. // 退出Word应用
  72. if (word != null)
  73. {
  74. word.Quit();
  75. #pragma warning disable CA1416 // 验证平台兼容性
  76. System.Runtime.InteropServices.Marshal.ReleaseComObject(word);
  77. #pragma warning restore CA1416 // 验证平台兼容性
  78. }
  79. }
  80. }
  81. private string GetDocxTxt(string filepath)
  82. {
  83. var oldtext = getDocxMainXml(filepath);
  84. var oldlines = ExtractWPTextFromXml(oldtext);
  85. oldtext = List2String(oldlines);
  86. return oldtext;
  87. }
  88. private string List2String(List<string> lines)
  89. {
  90. string[] array = { "权 利 要 求 书", "说 明 书 摘 要", "说 明 书" , "摘 要 附 图", "说 明 书 附 图" };
  91. StringBuilder sb = new StringBuilder();
  92. string lastBlock = string.Empty;
  93. foreach (var line in lines)
  94. {
  95. if (!string.IsNullOrEmpty(line))
  96. {
  97. sb.Append(line.Trim() + "\r\n");
  98. if(Array.Exists(array, element => element == line.Trim()))
  99. {
  100. lastBlock = line.Trim();
  101. }
  102. else
  103. {
  104. switch(lastBlock) {
  105. case "权 利 要 求 书":
  106. this.Claim = this.Claim + "\r\n" + line;
  107. break;
  108. case "说 明 书 摘 要":
  109. this.Abstract = this.Abstract + "\r\n" + line;
  110. break;
  111. case "说 明 书":
  112. this.FullText = this.FullText + "\r\n" + line;
  113. break;
  114. }
  115. }
  116. }
  117. }
  118. this.Abstract = string.IsNullOrEmpty(this.Abstract)?string.Empty: this.Abstract.Trim();
  119. this.Claim = string.IsNullOrEmpty(this.Claim) ? string.Empty : this.Claim.Trim();
  120. this.FullText = string.IsNullOrEmpty(this.FullText) ? string.Empty : this.FullText.Trim();
  121. return sb.ToString();
  122. }
  123. private string getDocxMainXml(string filePath)
  124. {
  125. string text = string.Empty;
  126. using (Package package = Package.Open(filePath, FileMode.Open))
  127. {
  128. var Parts = package.GetParts();
  129. foreach (var part in Parts)
  130. {
  131. if (part.ContentType.StartsWith("application/vnd.openxmlformats-officedocument.wordprocessingml.document.main"))
  132. {
  133. using (Stream stream = part.GetStream())
  134. {
  135. StreamReader reader = new StreamReader(stream);
  136. text = reader.ReadToEnd();
  137. break;
  138. }
  139. }
  140. }
  141. return text;
  142. }
  143. }
  144. private List<string> ExtractWPTextFromXml(string xmlText)
  145. {
  146. List<string> lines = new List<string>();
  147. // 使用正则表达式匹配 <w:t> 标签的内容
  148. MatchCollection matches = Regex.Matches(xmlText, "(<w:p\\s.*?>|<w:p>)(.*?)</w:p>");
  149. foreach (Match match in matches)
  150. {
  151. lines.Add(ExtractWtTextFromXml(match.Groups[2].Value));
  152. }
  153. return lines;
  154. }
  155. private string ExtractWtTextFromXml(string xmlText)
  156. {
  157. // 使用正则表达式匹配 <w:t> 标签的内容
  158. MatchCollection matches = Regex.Matches(xmlText, "(<w:t\\s.*?>|<w:t>)(.*?)</w:t>");
  159. StringBuilder sb = new StringBuilder();
  160. foreach (Match match in matches)
  161. {
  162. sb.Append(match.Groups[2].Value);
  163. }
  164. return sb.ToString();
  165. }
  166. }
  167. /// <summary>
  168. /// 原文档路径
  169. /// </summary>
  170. public PatentDocument oldDocument { get; set; }
  171. /// <summary>
  172. /// 修订后文档路径
  173. /// </summary>
  174. public PatentDocument newDocument { get; set; }
  175. /// <summary>
  176. /// 权力要求比较结果
  177. /// </summary>
  178. public CompareResult ClaimResult { get; set; }
  179. /// <summary>
  180. /// 摘要比较结果
  181. /// </summary>
  182. public CompareResult AbstractResult { get; set; }
  183. /// <summary>
  184. /// 说明书比较结果
  185. /// </summary>
  186. public CompareResult FulltextResult { get; set; }
  187. /// <summary>
  188. /// 所有文字比较结果
  189. /// </summary>
  190. public CompareResult AllStringResult { get; set; }
  191. /// <summary>
  192. /// 比较两个文档
  193. /// </summary>
  194. /// <param name="oldFile"></param>
  195. /// <param name="newFile"></param>
  196. public void Compare(string oldFile, string newFile)
  197. {
  198. this.oldDocument =new PatentDocument(oldFile);
  199. this.newDocument =new PatentDocument(newFile);
  200. this.ClaimResult = StringCompare(this.oldDocument.Claim,this.newDocument.Claim);
  201. this.AbstractResult = StringCompare(this.oldDocument.Abstract, this.newDocument.Abstract);
  202. this.FulltextResult = StringCompare(this.oldDocument.FullText, this.newDocument.FullText);
  203. this.AllStringResult = StringCompare(this.oldDocument.DocumentString, this.newDocument.DocumentString);
  204. }
  205. /// <summary>
  206. /// 比较两个文档
  207. /// </summary>
  208. /// <exception cref="ApplicationException"></exception>
  209. public CompareResult StringCompare(string oldtext,string newtext)
  210. {
  211. CompareResult result = new CompareResult();
  212. var differ = new Differ();
  213. if(oldtext == null) { oldtext = ""; }
  214. if(newtext == null) { newtext = ""; }
  215. result.oldWordCount = oldtext.Length;
  216. result.newWordCount = newtext.Length;
  217. var diff = differ.CreateCharacterDiffs(oldtext, newtext, true);
  218. //result.EditCount = diff.DiffBlocks.Count;
  219. int lastPos = 0;
  220. string _CompareResultString = "";
  221. string lastResult = "";
  222. List<string> ModifyList = new List<string>();
  223. foreach (var change in diff.DiffBlocks)
  224. {
  225. string strModifyStr = "";
  226. lastResult += oldtext.Substring(lastPos, change.DeleteStartA - lastPos);
  227. _CompareResultString += oldtext.Substring(lastPos, change.DeleteStartA - lastPos);
  228. lastPos = change.DeleteStartA + change.DeleteCountA;
  229. if (change.DeleteCountA > 0)
  230. {
  231. strModifyStr += $"<strike style=\"text-decoration: line-through; color: red;\">{oldtext.Substring(change.DeleteStartA, change.DeleteCountA)}</strike>";
  232. _CompareResultString += $"<strike style=\"text-decoration: line-through; color: red;\">{oldtext.Substring(change.DeleteStartA, change.DeleteCountA)}</strike>";
  233. }
  234. if (change.InsertCountB > 0)
  235. {
  236. strModifyStr += $"<u style=\"text-decoration: underline; color: blue;\">{newtext.Substring(change.InsertStartB, change.InsertCountB)}</u>";
  237. _CompareResultString += $"<u style=\"text-decoration: underline; color: blue;\">{newtext.Substring(change.InsertStartB, change.InsertCountB)}</u>";
  238. lastResult += newtext.Substring(change.InsertStartB, change.InsertCountB);
  239. }
  240. if(!ModifyList.Contains(strModifyStr))
  241. {
  242. ModifyList.Add(strModifyStr);
  243. result.DeleteCount += change.DeleteCountA;
  244. result.InsertCount += change.InsertCountB;
  245. result.EditCount += 1;
  246. }
  247. }
  248. lastResult += oldtext.Substring(lastPos);
  249. _CompareResultString += oldtext.Substring(lastPos);
  250. _CompareResultString = _CompareResultString.Replace("\r\n", "<br/>");
  251. result.CompareResultString = _CompareResultString;
  252. result.TextSimilarity = CosineSimilarity.Calculate(oldtext, newtext);
  253. return result;
  254. }
  255. }
  256. }