DOCX.cs 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.IO.Compression;
  5. using System.Xml;
  6. using Newtonsoft.Json;
  7. namespace DOCX
  8. {
  9. public class Docx : IDisposable
  10. {
  11. private readonly ZipArchive _zip;
  12. private readonly string _zipPath;
  13. private readonly XmlNamespaceManager _ns = new XmlNamespaceManager(new NameTable());
  14. private readonly Dictionary<string, string> _namespaces = new Dictionary<string, string>
  15. {
  16. {"w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main"}
  17. };
  18. private void LoadNamespaces()
  19. {
  20. foreach (var item in _namespaces)
  21. {
  22. _ns.AddNamespace(item.Key, item.Value);
  23. }
  24. }
  25. public Docx(string path)
  26. {
  27. _zip = ZipFile.Open(path, ZipArchiveMode.Update);
  28. _zipPath = path;
  29. LoadNamespaces();
  30. }
  31. public Docx(ZipArchive zipArchive)
  32. {
  33. _zip = zipArchive;
  34. LoadNamespaces();
  35. }
  36. private (XmlDocument doc, string message) GetXML(ZipArchiveEntry entry)
  37. {
  38. XmlDocument doc = new XmlDocument()
  39. {
  40. PreserveWhitespace = true // Disables auto-indent
  41. };
  42. try
  43. {
  44. using (StreamReader sr = new StreamReader(entry.Open()))
  45. {
  46. doc.Load(sr);
  47. }
  48. }
  49. catch (Exception e)
  50. {
  51. return (null, $"Error reading {entry.Name}!\n{e}");
  52. }
  53. return (doc, "OK");
  54. }
  55. private (bool status, string message) SaveXML(XmlDocument doc, ZipArchiveEntry entry)
  56. {
  57. try
  58. {
  59. using (var sr = entry.Open())
  60. {
  61. sr.SetLength(doc.OuterXml.Length);
  62. using (StreamWriter sw = new StreamWriter(sr))
  63. {
  64. doc.Save(sw);
  65. }
  66. }
  67. }
  68. catch (Exception e)
  69. {
  70. return (false, $"Error saving {entry.Name}!\n{e}");
  71. }
  72. return (true, "OK");
  73. }
  74. private (bool status, string message) AddTrackRevisions(ZipArchiveEntry settings)
  75. {
  76. var loadResult = GetXML(settings);
  77. if (loadResult.doc == null)
  78. return (false, loadResult.message);
  79. XmlDocument doc = loadResult.doc;
  80. if (doc.SelectSingleNode("//w:trackRevisions", _ns) != null) return (true, "No change needed.");
  81. XmlElement trackRevisions = doc.CreateElement("w", "trackRevisions", _namespaces["w"]);
  82. if (doc.DocumentElement == null)
  83. return (false, "No root element in settings.xml!");
  84. doc.DocumentElement.AppendChild(trackRevisions);
  85. return SaveXML(doc, settings);
  86. }
  87. public (bool status, string message) EnableTrackedChanges()
  88. {
  89. ZipArchiveEntry settings = _zip.GetEntry(@"word/settings.xml");
  90. if (settings == null)
  91. return (false,
  92. "Can't access settings.xml!");
  93. var result = AddTrackRevisions(settings);
  94. return !result.status ? (false, result.message) : (true, "OK");
  95. }
  96. private Dictionary<string, string> _authors = new Dictionary<string, string>();
  97. private string AnonymizeName(string name)
  98. {
  99. if (_authors.TryGetValue(name, out var anonymousName))
  100. return anonymousName;
  101. anonymousName = $"Author{_authors.Count + 1}";
  102. _authors.Add(name, anonymousName);
  103. return anonymousName;
  104. }
  105. private (bool status, string message) AnonymizeAuthors(ZipArchiveEntry comments)
  106. {
  107. var loadResult = GetXML(comments);
  108. if (loadResult.doc == null)
  109. return (false, loadResult.message);
  110. XmlDocument doc = loadResult.doc;
  111. var commentNodes = doc.SelectNodes("//w:comment", _ns);
  112. if (commentNodes == null)
  113. return (false, "There are no comments!");
  114. foreach (XmlNode node in commentNodes)
  115. {
  116. var author = node.Attributes["w:author"];
  117. author.Value = AnonymizeName(author.Value);
  118. }
  119. return SaveXML(doc, comments);
  120. }
  121. private void SaveAuthors()
  122. {
  123. string path = Path.ChangeExtension(_zipPath, "json");
  124. using (StreamWriter sw = new StreamWriter(path))
  125. using (JsonWriter writer = new JsonTextWriter(sw))
  126. {
  127. JsonSerializer serializer = new JsonSerializer
  128. {
  129. NullValueHandling = NullValueHandling.Ignore
  130. };
  131. serializer.Serialize(writer, _authors);
  132. }
  133. }
  134. public (bool status, string message) AnonymizeComments()
  135. {
  136. ZipArchiveEntry comments = _zip.GetEntry(@"word/comments.xml");
  137. if (comments == null)
  138. return (false,
  139. "Can't access comments.xml!");
  140. var result = AnonymizeAuthors(comments);
  141. if (!result.status) return (false, result.message);
  142. SaveAuthors();
  143. return (true, "OK");
  144. }
  145. public void Dispose()
  146. {
  147. Dispose(true);
  148. GC.SuppressFinalize(this);
  149. }
  150. ~Docx()
  151. {
  152. Dispose(false);
  153. }
  154. protected virtual void Dispose(bool disposing)
  155. {
  156. if (disposing)
  157. {
  158. _zip.Dispose();
  159. }
  160. }
  161. }
  162. }