CompareDocx.cs 13 KB

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