CompareDocx.cs 13 KB

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