Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Xml.Linq;
  6. using System.Text.RegularExpressions;
  7. using System.IO.Packaging;
  8. using System.IO;
  9. namespace Novacode
  10. {
  11. public abstract class Container : DocXElement
  12. {
  13. /// <summary>
  14. /// Returns a list of all Paragraphs inside this container.
  15. /// </summary>
  16. /// <example>
  17. /// <code>
  18. /// Load a document.
  19. /// using (DocX document = DocX.Load(@"Test.docx"))
  20. /// {
  21. /// // All Paragraphs in this document.
  22. /// List<Paragraph> documentParagraphs = document.Paragraphs;
  23. ///
  24. /// // Make sure this document contains at least one Table.
  25. /// if (document.Tables.Count() > 0)
  26. /// {
  27. /// // Get the first Table in this document.
  28. /// Table t = document.Tables[0];
  29. ///
  30. /// // All Paragraphs in this Table.
  31. /// List<Paragraph> tableParagraphs = t.Paragraphs;
  32. ///
  33. /// // Make sure this Table contains at least one Row.
  34. /// if (t.Rows.Count() > 0)
  35. /// {
  36. /// // Get the first Row in this document.
  37. /// Row r = t.Rows[0];
  38. ///
  39. /// // All Paragraphs in this Row.
  40. /// List<Paragraph> rowParagraphs = r.Paragraphs;
  41. ///
  42. /// // Make sure this Row contains at least one Cell.
  43. /// if (r.Cells.Count() > 0)
  44. /// {
  45. /// // Get the first Cell in this document.
  46. /// Cell c = r.Cells[0];
  47. ///
  48. /// // All Paragraphs in this Cell.
  49. /// List<Paragraph> cellParagraphs = c.Paragraphs;
  50. /// }
  51. /// }
  52. /// }
  53. ///
  54. /// // Save all changes to this document.
  55. /// document.Save();
  56. /// }// Release this document from memory.
  57. /// </code>
  58. /// </example>
  59. public virtual List<Paragraph> Paragraphs
  60. {
  61. get
  62. {
  63. List<Paragraph> paragraphs = GetParagraphs();
  64. foreach (var p in paragraphs)
  65. {
  66. if ((p.Xml.ElementsAfterSelf().FirstOrDefault() != null) && (p.Xml.ElementsAfterSelf().First().Name.Equals(DocX.w + "tbl")))
  67. p.FollowingTable = new Table(this.Document, p.Xml.ElementsAfterSelf().First());
  68. }
  69. return paragraphs;
  70. }
  71. }
  72. internal List<Paragraph> GetParagraphs()
  73. {
  74. // Need some memory that can be updated by the recursive search.
  75. int index = 0;
  76. List<Paragraph> paragraphs = new List<Paragraph>();
  77. GetParagraphsRecursive(Xml, ref index, ref paragraphs);
  78. return paragraphs;
  79. }
  80. internal void GetParagraphsRecursive(XElement Xml, ref int index, ref List<Paragraph> paragraphs)
  81. {
  82. // sdtContent are for PageNumbers inside Headers or Footers, don't go any deeper.
  83. if (Xml.Name.LocalName == "sdtContent")
  84. return;
  85. if (Xml.Name.LocalName == "p")
  86. {
  87. paragraphs.Add(new Paragraph(Document, Xml, index));
  88. index += HelperFunctions.GetText(Xml).Length;
  89. }
  90. else
  91. {
  92. if (Xml.HasElements)
  93. foreach (XElement e in Xml.Elements())
  94. GetParagraphsRecursive(e, ref index, ref paragraphs);
  95. }
  96. }
  97. public virtual List<Table> Tables
  98. {
  99. get
  100. {
  101. List<Table> tables =
  102. (
  103. from t in Xml.Descendants(DocX.w + "tbl")
  104. select new Table(Document, t)
  105. ).ToList();
  106. return tables;
  107. }
  108. }
  109. public virtual List<Hyperlink> Hyperlinks
  110. {
  111. get
  112. {
  113. List<Hyperlink> hyperlinks = new List<Hyperlink>();
  114. foreach (Paragraph p in Paragraphs)
  115. hyperlinks.AddRange(p.Hyperlinks);
  116. return hyperlinks;
  117. }
  118. }
  119. public virtual List<Picture> Pictures
  120. {
  121. get
  122. {
  123. List<Picture> pictures = new List<Picture>();
  124. foreach (Paragraph p in Paragraphs)
  125. pictures.AddRange(p.Pictures);
  126. return pictures;
  127. }
  128. }
  129. /// <summary>
  130. /// Sets the Direction of content.
  131. /// </summary>
  132. /// <param name="direction">Direction either LeftToRight or RightToLeft</param>
  133. /// <example>
  134. /// Set the Direction of content in a Paragraph to RightToLeft.
  135. /// <code>
  136. /// // Load a document.
  137. /// using (DocX document = DocX.Load(@"Test.docx"))
  138. /// {
  139. /// // Get the first Paragraph from this document.
  140. /// Paragraph p = document.InsertParagraph();
  141. ///
  142. /// // Set the Direction of this Paragraph.
  143. /// p.Direction = Direction.RightToLeft;
  144. ///
  145. /// // Make sure the document contains at lest one Table.
  146. /// if (document.Tables.Count() > 0)
  147. /// {
  148. /// // Get the first Table from this document.
  149. /// Table t = document.Tables[0];
  150. ///
  151. /// /*
  152. /// * Set the direction of the entire Table.
  153. /// * Note: The same function is available at the Row and Cell level.
  154. /// */
  155. /// t.SetDirection(Direction.RightToLeft);
  156. /// }
  157. ///
  158. /// // Save all changes to this document.
  159. /// document.Save();
  160. /// }// Release this document from memory.
  161. /// </code>
  162. /// </example>
  163. public virtual void SetDirection(Direction direction)
  164. {
  165. foreach (Paragraph p in Paragraphs)
  166. p.Direction = direction;
  167. }
  168. public virtual List<int> FindAll(string str)
  169. {
  170. return FindAll(str, RegexOptions.None);
  171. }
  172. public virtual List<int> FindAll(string str, RegexOptions options)
  173. {
  174. List<int> list = new List<int>();
  175. foreach (Paragraph p in Paragraphs)
  176. {
  177. List<int> indexes = p.FindAll(str, options);
  178. for (int i = 0; i < indexes.Count(); i++)
  179. indexes[0] += p.startIndex;
  180. list.AddRange(indexes);
  181. }
  182. return list;
  183. }
  184. /// <summary>
  185. /// Find all unique instances of the given Regex Pattern,
  186. /// returning the list of the unique strings found
  187. /// </summary>
  188. /// <param name="str"></param>
  189. /// <param name="options"></param>
  190. /// <returns></returns>
  191. public virtual List<string> FindUniqueByPattern(string pattern, RegexOptions options)
  192. {
  193. List<string> rawResults = new List<string>();
  194. foreach (Paragraph p in Paragraphs)
  195. { // accumulate the search results from all paragraphs
  196. List<string> partials = p.FindAllByPattern(pattern, options);
  197. rawResults.AddRange(partials);
  198. }
  199. // this dictionary is used to collect results and test for uniqueness
  200. Dictionary<string, int> uniqueResults = new Dictionary<string, int>();
  201. foreach (string currValue in rawResults)
  202. {
  203. if (!uniqueResults.ContainsKey(currValue))
  204. { // if the dictionary doesn't have it, add it
  205. uniqueResults.Add(currValue, 0);
  206. }
  207. }
  208. return uniqueResults.Keys.ToList(); // return the unique list of results
  209. }
  210. public virtual void ReplaceText(string oldValue, string newValue, bool trackChanges = false, RegexOptions options = RegexOptions.None, Formatting newFormatting = null, Formatting matchFormatting = null, MatchFormattingOptions fo = MatchFormattingOptions.SubsetMatch)
  211. {
  212. // ReplaceText in Headers of the document.
  213. Headers headers = Document.Headers;
  214. List<Header> headerList = new List<Header> { headers.first, headers.even, headers.odd };
  215. foreach (Header h in headerList)
  216. if (h != null)
  217. foreach (Paragraph p in h.Paragraphs)
  218. p.ReplaceText(oldValue, newValue, trackChanges, options, newFormatting, matchFormatting, fo);
  219. // ReplaceText int main body of document.
  220. foreach (Paragraph p in Paragraphs)
  221. p.ReplaceText(oldValue, newValue, trackChanges, options, newFormatting, matchFormatting, fo);
  222. // ReplaceText in Footers of the document.
  223. Footers footers = Document.Footers;
  224. List<Footer> footerList = new List<Footer> { footers.first, footers.even, footers.odd };
  225. foreach (Footer f in footerList)
  226. if (f != null)
  227. foreach (Paragraph p in f.Paragraphs)
  228. p.ReplaceText(oldValue, newValue, trackChanges, options, newFormatting, matchFormatting, fo);
  229. }
  230. public virtual Paragraph InsertParagraph(int index, string text, bool trackChanges)
  231. {
  232. return InsertParagraph(index, text, trackChanges, null);
  233. }
  234. public virtual Paragraph InsertParagraph()
  235. {
  236. return InsertParagraph(string.Empty, false);
  237. }
  238. public virtual Paragraph InsertParagraph(int index, Paragraph p)
  239. {
  240. XElement newXElement = new XElement(p.Xml);
  241. p.Xml = newXElement;
  242. Paragraph paragraph = HelperFunctions.GetFirstParagraphEffectedByInsert(Document, index);
  243. if (paragraph == null)
  244. Xml.Add(p.Xml);
  245. else
  246. {
  247. XElement[] split = HelperFunctions.SplitParagraph(paragraph, index - paragraph.startIndex);
  248. paragraph.Xml.ReplaceWith
  249. (
  250. split[0],
  251. newXElement,
  252. split[1]
  253. );
  254. }
  255. return p;
  256. }
  257. public virtual Paragraph InsertParagraph(Paragraph p)
  258. {
  259. #region Styles
  260. XDocument style_document;
  261. if (p.styles.Count() > 0)
  262. {
  263. Uri style_package_uri = new Uri("/word/styles.xml", UriKind.Relative);
  264. if (!Document.package.PartExists(style_package_uri))
  265. {
  266. PackagePart style_package = Document.package.CreatePart(style_package_uri, "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml");
  267. using (TextWriter tw = new StreamWriter(style_package.GetStream()))
  268. {
  269. style_document = new XDocument
  270. (
  271. new XDeclaration("1.0", "UTF-8", "yes"),
  272. new XElement(XName.Get("styles", DocX.w.NamespaceName))
  273. );
  274. style_document.Save(tw);
  275. }
  276. }
  277. PackagePart styles_document = Document.package.GetPart(style_package_uri);
  278. using (TextReader tr = new StreamReader(styles_document.GetStream()))
  279. {
  280. style_document = XDocument.Load(tr);
  281. XElement styles_element = style_document.Element(XName.Get("styles", DocX.w.NamespaceName));
  282. var ids = from d in styles_element.Descendants(XName.Get("style", DocX.w.NamespaceName))
  283. let a = d.Attribute(XName.Get("styleId", DocX.w.NamespaceName))
  284. where a != null
  285. select a.Value;
  286. foreach (XElement style in p.styles)
  287. {
  288. // If styles_element does not contain this element, then add it.
  289. if (!ids.Contains(style.Attribute(XName.Get("styleId", DocX.w.NamespaceName)).Value))
  290. styles_element.Add(style);
  291. }
  292. }
  293. using (TextWriter tw = new StreamWriter(styles_document.GetStream()))
  294. style_document.Save(tw);
  295. }
  296. #endregion
  297. XElement newXElement = new XElement(p.Xml);
  298. Xml.Add(newXElement);
  299. int index = 0;
  300. if (Document.paragraphLookup.Keys.Count() > 0)
  301. {
  302. index = Document.paragraphLookup.Last().Key;
  303. if (Document.paragraphLookup.Last().Value.Text.Length == 0)
  304. index++;
  305. else
  306. index += Document.paragraphLookup.Last().Value.Text.Length;
  307. }
  308. Paragraph newParagraph = new Paragraph(Document, newXElement, index);
  309. Document.paragraphLookup.Add(index, newParagraph);
  310. return newParagraph;
  311. }
  312. public virtual Paragraph InsertParagraph(int index, string text, bool trackChanges, Formatting formatting)
  313. {
  314. Paragraph newParagraph = new Paragraph(Document, new XElement(DocX.w + "p"), index);
  315. newParagraph.InsertText(0, text, trackChanges, formatting);
  316. Paragraph firstPar = HelperFunctions.GetFirstParagraphEffectedByInsert(Document, index);
  317. if (firstPar != null)
  318. {
  319. XElement[] splitParagraph = HelperFunctions.SplitParagraph(firstPar, index - firstPar.startIndex);
  320. firstPar.Xml.ReplaceWith
  321. (
  322. splitParagraph[0],
  323. newParagraph.Xml,
  324. splitParagraph[1]
  325. );
  326. }
  327. else
  328. Xml.Add(newParagraph);
  329. return newParagraph;
  330. }
  331. public virtual Paragraph InsertParagraph(string text)
  332. {
  333. return InsertParagraph(text, false, new Formatting());
  334. }
  335. public virtual Paragraph InsertParagraph(string text, bool trackChanges)
  336. {
  337. return InsertParagraph(text, trackChanges, new Formatting());
  338. }
  339. public virtual Paragraph InsertParagraph(string text, bool trackChanges, Formatting formatting)
  340. {
  341. XElement newParagraph = new XElement
  342. (
  343. XName.Get("p", DocX.w.NamespaceName), new XElement(XName.Get("pPr", DocX.w.NamespaceName)), HelperFunctions.FormatInput(text, formatting.Xml)
  344. );
  345. if (trackChanges)
  346. newParagraph = HelperFunctions.CreateEdit(EditType.ins, DateTime.Now, newParagraph);
  347. Xml.Add(newParagraph);
  348. return Paragraphs.Last();
  349. }
  350. public Table InsertTable(int coloumnCount, int rowCount)
  351. {
  352. XElement newTable = HelperFunctions.CreateTable(rowCount, coloumnCount);
  353. Xml.Elements().First().Add(newTable);
  354. return new Table(Document, newTable);
  355. }
  356. public Table InsertTable(int index, int coloumnCount, int rowCount)
  357. {
  358. XElement newTable = HelperFunctions.CreateTable(rowCount, coloumnCount);
  359. Paragraph p = HelperFunctions.GetFirstParagraphEffectedByInsert(Document, index);
  360. if (p == null)
  361. Xml.Elements().First().AddFirst(newTable);
  362. else
  363. {
  364. XElement[] split = HelperFunctions.SplitParagraph(p, index - p.startIndex);
  365. p.Xml.ReplaceWith
  366. (
  367. split[0],
  368. newTable,
  369. split[1]
  370. );
  371. }
  372. return new Table(Document, newTable);
  373. }
  374. public Table InsertTable(Table t)
  375. {
  376. XElement newXElement = new XElement(t.Xml);
  377. Xml.Add(newXElement);
  378. Table newTable = new Table(Document, newXElement);
  379. newTable.Design = t.Design;
  380. return newTable;
  381. }
  382. public Table InsertTable(int index, Table t)
  383. {
  384. Paragraph p = HelperFunctions.GetFirstParagraphEffectedByInsert(Document, index);
  385. XElement[] split = HelperFunctions.SplitParagraph(p, index - p.startIndex);
  386. XElement newXElement = new XElement(t.Xml);
  387. p.Xml.ReplaceWith
  388. (
  389. split[0],
  390. newXElement,
  391. split[1]
  392. );
  393. Table newTable = new Table(Document, newXElement);
  394. newTable.Design = t.Design;
  395. return newTable;
  396. }
  397. internal Container(DocX document, XElement xml)
  398. : base(document, xml)
  399. {
  400. }
  401. }
  402. }