You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Container.cs 34KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960
  1. using System;
  2. using System.IO;
  3. using System.Linq;
  4. using System.Xml.Linq;
  5. using System.IO.Packaging;
  6. using System.Collections.Generic;
  7. using System.Text.RegularExpressions;
  8. using System.Collections.ObjectModel;
  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. /// <![CDATA[ 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. /// <![CDATA[ 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. /// <![CDATA[ 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. /// <![CDATA[ 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 ReadOnlyCollection<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. p.ParentContainer = GetParentFromXmlName(p.Xml.Ancestors().First().Name.LocalName);
  69. if (p.IsListItem)
  70. {
  71. GetListItemType(p);
  72. }
  73. }
  74. return paragraphs.AsReadOnly();
  75. }
  76. }
  77. public virtual ReadOnlyCollection<Paragraph> ParagraphsDeepSearch
  78. {
  79. get
  80. {
  81. List<Paragraph> paragraphs = GetParagraphs(true);
  82. foreach (var p in paragraphs)
  83. {
  84. if ((p.Xml.ElementsAfterSelf().FirstOrDefault() != null) && (p.Xml.ElementsAfterSelf().First().Name.Equals(DocX.w + "tbl")))
  85. p.FollowingTable = new Table(this.Document, p.Xml.ElementsAfterSelf().First());
  86. p.ParentContainer = GetParentFromXmlName(p.Xml.Ancestors().First().Name.LocalName);
  87. if (p.IsListItem)
  88. {
  89. GetListItemType(p);
  90. }
  91. }
  92. return paragraphs.AsReadOnly();
  93. }
  94. }
  95. /// <summary>
  96. /// Removes paragraph at specified position
  97. /// </summary>
  98. /// <param name="index">Index of paragraph to remove</param>
  99. /// <returns>True if removed</returns>
  100. public bool RemoveParagraphAt(int index)
  101. {
  102. int i = 0;
  103. foreach (var paragraph in Xml.Descendants(DocX.w + "p"))
  104. {
  105. if (i == index)
  106. {
  107. paragraph.Remove();
  108. return true;
  109. }
  110. ++i;
  111. }
  112. return false;
  113. }
  114. /// <summary>
  115. /// Removes paragraph
  116. /// </summary>
  117. /// <param name="p">Paragraph to remove</param>
  118. /// <returns>True if removed</returns>
  119. public bool RemoveParagraph(Paragraph p)
  120. {
  121. foreach (var paragraph in Xml.Descendants(DocX.w + "p"))
  122. {
  123. if (paragraph.Equals(p.Xml))
  124. {
  125. paragraph.Remove();
  126. return true;
  127. }
  128. }
  129. return false;
  130. }
  131. public virtual List<Section> Sections
  132. {
  133. get
  134. {
  135. var allParas = Paragraphs;
  136. var parasInASection = new List<Paragraph>();
  137. var sections = new List<Section>();
  138. foreach (var para in allParas)
  139. {
  140. var sectionInPara = para.Xml.Descendants().FirstOrDefault(s => s.Name.LocalName == "sectPr");
  141. if (sectionInPara == null)
  142. {
  143. parasInASection.Add(para);
  144. }
  145. else
  146. {
  147. parasInASection.Add(para);
  148. var section = new Section(Document, sectionInPara) { SectionParagraphs = parasInASection };
  149. sections.Add(section);
  150. parasInASection = new List<Paragraph>();
  151. }
  152. }
  153. XElement body = Xml.Element(XName.Get("body", DocX.w.NamespaceName));
  154. XElement baseSectionXml = body.Element(XName.Get("sectPr", DocX.w.NamespaceName));
  155. var baseSection = new Section(Document, baseSectionXml) { SectionParagraphs = parasInASection };
  156. sections.Add(baseSection);
  157. return sections;
  158. }
  159. }
  160. private void GetListItemType(Paragraph p)
  161. {
  162. var ilvlNode = p.ParagraphNumberProperties.Descendants().FirstOrDefault(el => el.Name.LocalName == "ilvl");
  163. var ilvlValue = ilvlNode.Attribute(DocX.w + "val").Value;
  164. var numIdNode = p.ParagraphNumberProperties.Descendants().FirstOrDefault(el => el.Name.LocalName == "numId");
  165. var numIdValue = numIdNode.Attribute(DocX.w + "val").Value;
  166. //find num node in numbering
  167. var numNodes = Document.numbering.Descendants().Where(n => n.Name.LocalName == "num");
  168. XElement numNode = numNodes.FirstOrDefault(node => node.Attribute(DocX.w + "numId").Value.Equals(numIdValue));
  169. if (numNode != null)
  170. {
  171. //Get abstractNumId node and its value from numNode
  172. var abstractNumIdNode = numNode.Descendants().First(n => n.Name.LocalName == "abstractNumId");
  173. var abstractNumNodeValue = abstractNumIdNode.Attribute(DocX.w + "val").Value;
  174. var abstractNumNodes = Document.numbering.Descendants().Where(n => n.Name.LocalName == "abstractNum");
  175. XElement abstractNumNode =
  176. abstractNumNodes.FirstOrDefault(node => node.Attribute(DocX.w + "abstractNumId").Value.Equals(abstractNumNodeValue));
  177. //Find lvl node
  178. var lvlNodes = abstractNumNode.Descendants().Where(n => n.Name.LocalName == "lvl");
  179. XElement lvlNode = null;
  180. foreach (XElement node in lvlNodes)
  181. {
  182. if (node.Attribute(DocX.w + "ilvl").Value.Equals(ilvlValue))
  183. {
  184. lvlNode = node;
  185. break;
  186. }
  187. }
  188. var numFmtNode = lvlNode.Descendants().First(n => n.Name.LocalName == "numFmt");
  189. p.ListItemType = GetListItemType(numFmtNode.Attribute(DocX.w + "val").Value);
  190. }
  191. }
  192. public ContainerType ParentContainer;
  193. internal List<Paragraph> GetParagraphs(bool deepSearch=false)
  194. {
  195. // Need some memory that can be updated by the recursive search.
  196. int index = 0;
  197. List<Paragraph> paragraphs = new List<Paragraph>();
  198. GetParagraphsRecursive(Xml, ref index, ref paragraphs, deepSearch);
  199. return paragraphs;
  200. }
  201. internal void GetParagraphsRecursive(XElement Xml, ref int index, ref List<Paragraph> paragraphs, bool deepSearch=false)
  202. {
  203. // sdtContent are for PageNumbers inside Headers or Footers, don't go any deeper.
  204. //if (Xml.Name.LocalName == "sdtContent")
  205. // return;
  206. var keepSearching = true;
  207. if (Xml.Name.LocalName == "p")
  208. {
  209. paragraphs.Add(new Paragraph(Document, Xml, index));
  210. index += HelperFunctions.GetText(Xml).Length;
  211. if (!deepSearch)
  212. keepSearching = false;
  213. }
  214. if (keepSearching && Xml.HasElements)
  215. {
  216. foreach (XElement e in Xml.Elements())
  217. {
  218. GetParagraphsRecursive(e, ref index, ref paragraphs, deepSearch);
  219. }
  220. }
  221. }
  222. public virtual List<Table> Tables
  223. {
  224. get
  225. {
  226. List<Table> tables =
  227. (
  228. from t in Xml.Descendants(DocX.w + "tbl")
  229. select new Table(Document, t)
  230. ).ToList();
  231. return tables;
  232. }
  233. }
  234. public virtual List<List> Lists
  235. {
  236. get
  237. {
  238. var lists = new List<List>();
  239. var list = new List(Document, Xml);
  240. foreach (var paragraph in Paragraphs)
  241. {
  242. if (paragraph.IsListItem)
  243. {
  244. if (list.CanAddListItem(paragraph))
  245. {
  246. list.AddItem(paragraph);
  247. }
  248. else
  249. {
  250. lists.Add(list);
  251. list = new List(Document, Xml);
  252. list.AddItem(paragraph);
  253. }
  254. }
  255. }
  256. lists.Add(list);
  257. return lists;
  258. }
  259. }
  260. public virtual List<Hyperlink> Hyperlinks
  261. {
  262. get
  263. {
  264. List<Hyperlink> hyperlinks = new List<Hyperlink>();
  265. foreach (Paragraph p in Paragraphs)
  266. hyperlinks.AddRange(p.Hyperlinks);
  267. return hyperlinks;
  268. }
  269. }
  270. public virtual List<Picture> Pictures
  271. {
  272. get
  273. {
  274. List<Picture> pictures = new List<Picture>();
  275. foreach (Paragraph p in Paragraphs)
  276. pictures.AddRange(p.Pictures);
  277. return pictures;
  278. }
  279. }
  280. /// <summary>
  281. /// Sets the Direction of content.
  282. /// </summary>
  283. /// <param name="direction">Direction either LeftToRight or RightToLeft</param>
  284. /// <example>
  285. /// Set the Direction of content in a Paragraph to RightToLeft.
  286. /// <code>
  287. /// // Load a document.
  288. /// using (DocX document = DocX.Load(@"Test.docx"))
  289. /// {
  290. /// // Get the first Paragraph from this document.
  291. /// Paragraph p = document.InsertParagraph();
  292. ///
  293. /// // Set the Direction of this Paragraph.
  294. /// p.Direction = Direction.RightToLeft;
  295. ///
  296. /// // Make sure the document contains at lest one Table.
  297. /// if (document.Tables.Count() > 0)
  298. /// {
  299. /// // Get the first Table from this document.
  300. /// Table t = document.Tables[0];
  301. ///
  302. /// /*
  303. /// * Set the direction of the entire Table.
  304. /// * Note: The same function is available at the Row and Cell level.
  305. /// */
  306. /// t.SetDirection(Direction.RightToLeft);
  307. /// }
  308. ///
  309. /// // Save all changes to this document.
  310. /// document.Save();
  311. /// }// Release this document from memory.
  312. /// </code>
  313. /// </example>
  314. public virtual void SetDirection(Direction direction)
  315. {
  316. foreach (Paragraph p in Paragraphs)
  317. p.Direction = direction;
  318. }
  319. public virtual List<int> FindAll(string str)
  320. {
  321. return FindAll(str, RegexOptions.None);
  322. }
  323. public virtual List<int> FindAll(string str, RegexOptions options)
  324. {
  325. List<int> list = new List<int>();
  326. foreach (Paragraph p in Paragraphs)
  327. {
  328. List<int> indexes = p.FindAll(str, options);
  329. for (int i = 0; i < indexes.Count(); i++)
  330. indexes[0] += p.startIndex;
  331. list.AddRange(indexes);
  332. }
  333. return list;
  334. }
  335. /// <summary>
  336. /// Find all unique instances of the given Regex Pattern,
  337. /// returning the list of the unique strings found
  338. /// </summary>
  339. /// <param name="pattern"></param>
  340. /// <param name="options"></param>
  341. /// <returns></returns>
  342. public virtual List<string> FindUniqueByPattern(string pattern, RegexOptions options)
  343. {
  344. List<string> rawResults = new List<string>();
  345. foreach (Paragraph p in Paragraphs)
  346. { // accumulate the search results from all paragraphs
  347. List<string> partials = p.FindAllByPattern(pattern, options);
  348. rawResults.AddRange(partials);
  349. }
  350. // this dictionary is used to collect results and test for uniqueness
  351. Dictionary<string, int> uniqueResults = new Dictionary<string, int>();
  352. foreach (string currValue in rawResults)
  353. {
  354. if (!uniqueResults.ContainsKey(currValue))
  355. { // if the dictionary doesn't have it, add it
  356. uniqueResults.Add(currValue, 0);
  357. }
  358. }
  359. return uniqueResults.Keys.ToList(); // return the unique list of results
  360. }
  361. 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)
  362. {
  363. if (oldValue == null || oldValue.Length == 0)
  364. throw new ArgumentException("oldValue cannot be null or empty", "oldValue");
  365. if (newValue == null)
  366. throw new ArgumentException("newValue cannot be null or empty", "newValue");
  367. // ReplaceText in Headers of the document.
  368. Headers headers = Document.Headers;
  369. List<Header> headerList = new List<Header> { headers.first, headers.even, headers.odd };
  370. foreach (Header h in headerList)
  371. if (h != null)
  372. foreach (Paragraph p in h.Paragraphs)
  373. p.ReplaceText(oldValue, newValue, trackChanges, options, newFormatting, matchFormatting, fo);
  374. // ReplaceText int main body of document.
  375. foreach (Paragraph p in Paragraphs)
  376. p.ReplaceText(oldValue, newValue, trackChanges, options, newFormatting, matchFormatting, fo);
  377. // ReplaceText in Footers of the document.
  378. Footers footers = Document.Footers;
  379. List<Footer> footerList = new List<Footer> { footers.first, footers.even, footers.odd };
  380. foreach (Footer f in footerList)
  381. if (f != null)
  382. foreach (Paragraph p in f.Paragraphs)
  383. p.ReplaceText(oldValue, newValue, trackChanges, options, newFormatting, matchFormatting, fo);
  384. }
  385. /// <summary>
  386. /// Removes all items with required formatting
  387. /// </summary>
  388. /// <returns>Numer of texts removed</returns>
  389. public int RemoveTextInGivenFormat(Formatting matchFormatting, MatchFormattingOptions fo = MatchFormattingOptions.SubsetMatch)
  390. {
  391. var deletedCount = 0;
  392. foreach (var x in Xml.Elements())
  393. {
  394. deletedCount += RemoveTextWithFormatRecursive(x, matchFormatting, fo);
  395. }
  396. return deletedCount;
  397. }
  398. internal int RemoveTextWithFormatRecursive(XElement element, Formatting matchFormatting, MatchFormattingOptions fo)
  399. {
  400. var deletedCount = 0;
  401. foreach (var x in element.Elements())
  402. {
  403. if ("rPr".Equals(x.Name.LocalName))
  404. {
  405. if (HelperFunctions.ContainsEveryChildOf(matchFormatting.Xml, x, fo))
  406. {
  407. x.Parent.Remove();
  408. ++deletedCount;
  409. }
  410. }
  411. deletedCount += RemoveTextWithFormatRecursive(x, matchFormatting, fo);
  412. }
  413. return deletedCount;
  414. }
  415. public virtual void InsertAtBookmark(string toInsert, string bookmarkName)
  416. {
  417. if (bookmarkName.IsNullOrWhiteSpace())
  418. throw new ArgumentException("bookmark cannot be null or empty", "bookmarkName");
  419. var headerCollection = Document.Headers;
  420. var headers = new List<Header> { headerCollection.first, headerCollection.even, headerCollection.odd };
  421. foreach (var header in headers.Where(x => x != null))
  422. foreach (var paragraph in header.Paragraphs)
  423. paragraph.InsertAtBookmark(toInsert, bookmarkName);
  424. foreach (var paragraph in Paragraphs)
  425. paragraph.InsertAtBookmark(toInsert, bookmarkName);
  426. var footerCollection = Document.Footers;
  427. var footers = new List<Footer> { footerCollection.first, footerCollection.even, footerCollection.odd };
  428. foreach (var footer in footers.Where(x => x != null))
  429. foreach (var paragraph in footer.Paragraphs)
  430. paragraph.InsertAtBookmark(toInsert, bookmarkName);
  431. }
  432. public string[] ValidateBookmarks(params string[] bookmarkNames)
  433. {
  434. var headers = new[] {Document.Headers.first, Document.Headers.even, Document.Headers.odd}.Where(h => h != null).ToList();
  435. var footers = new[] {Document.Footers.first, Document.Footers.even, Document.Footers.odd}.Where(f => f != null).ToList();
  436. var nonMatching = new List<string>();
  437. foreach (var bookmarkName in bookmarkNames)
  438. {
  439. if (headers.SelectMany(h => h.Paragraphs).Any(p => p.ValidateBookmark(bookmarkName))) return new string[0];
  440. if (footers.SelectMany(h => h.Paragraphs).Any(p => p.ValidateBookmark(bookmarkName))) return new string[0];
  441. if (Paragraphs.Any(p => p.ValidateBookmark(bookmarkName))) return new string[0];
  442. nonMatching.Add(bookmarkName);
  443. }
  444. return nonMatching.ToArray();
  445. }
  446. public virtual Paragraph InsertParagraph(int index, string text, bool trackChanges)
  447. {
  448. return InsertParagraph(index, text, trackChanges, null);
  449. }
  450. public virtual Paragraph InsertParagraph()
  451. {
  452. return InsertParagraph(string.Empty, false);
  453. }
  454. public virtual Paragraph InsertParagraph(int index, Paragraph p)
  455. {
  456. XElement newXElement = new XElement(p.Xml);
  457. p.Xml = newXElement;
  458. Paragraph paragraph = HelperFunctions.GetFirstParagraphEffectedByInsert(Document, index);
  459. if (paragraph == null)
  460. Xml.Add(p.Xml);
  461. else
  462. {
  463. XElement[] split = HelperFunctions.SplitParagraph(paragraph, index - paragraph.startIndex);
  464. paragraph.Xml.ReplaceWith
  465. (
  466. split[0],
  467. newXElement,
  468. split[1]
  469. );
  470. }
  471. GetParent(p);
  472. return p;
  473. }
  474. public virtual Paragraph InsertParagraph(Paragraph p)
  475. {
  476. #region Styles
  477. XDocument style_document;
  478. if (p.styles.Count() > 0)
  479. {
  480. Uri style_package_uri = new Uri("/word/styles.xml", UriKind.Relative);
  481. if (!Document.package.PartExists(style_package_uri))
  482. {
  483. PackagePart style_package = Document.package.CreatePart(style_package_uri, "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml", CompressionOption.Maximum);
  484. using (TextWriter tw = new StreamWriter(style_package.GetStream()))
  485. {
  486. style_document = new XDocument
  487. (
  488. new XDeclaration("1.0", "UTF-8", "yes"),
  489. new XElement(XName.Get("styles", DocX.w.NamespaceName))
  490. );
  491. style_document.Save(tw);
  492. }
  493. }
  494. PackagePart styles_document = Document.package.GetPart(style_package_uri);
  495. using (TextReader tr = new StreamReader(styles_document.GetStream()))
  496. {
  497. style_document = XDocument.Load(tr);
  498. XElement styles_element = style_document.Element(XName.Get("styles", DocX.w.NamespaceName));
  499. var ids = from d in styles_element.Descendants(XName.Get("style", DocX.w.NamespaceName))
  500. let a = d.Attribute(XName.Get("styleId", DocX.w.NamespaceName))
  501. where a != null
  502. select a.Value;
  503. foreach (XElement style in p.styles)
  504. {
  505. // If styles_element does not contain this element, then add it.
  506. if (!ids.Contains(style.Attribute(XName.Get("styleId", DocX.w.NamespaceName)).Value))
  507. styles_element.Add(style);
  508. }
  509. }
  510. using (TextWriter tw = new StreamWriter(styles_document.GetStream()))
  511. style_document.Save(tw);
  512. }
  513. #endregion
  514. XElement newXElement = new XElement(p.Xml);
  515. Xml.Add(newXElement);
  516. int index = 0;
  517. if (Document.paragraphLookup.Keys.Count() > 0)
  518. {
  519. index = Document.paragraphLookup.Last().Key;
  520. if (Document.paragraphLookup.Last().Value.Text.Length == 0)
  521. index++;
  522. else
  523. index += Document.paragraphLookup.Last().Value.Text.Length;
  524. }
  525. Paragraph newParagraph = new Paragraph(Document, newXElement, index);
  526. Document.paragraphLookup.Add(index, newParagraph);
  527. GetParent(newParagraph);
  528. return newParagraph;
  529. }
  530. public virtual Paragraph InsertParagraph(int index, string text, bool trackChanges, Formatting formatting)
  531. {
  532. Paragraph newParagraph = new Paragraph(Document, new XElement(DocX.w + "p"), index);
  533. newParagraph.InsertText(0, text, trackChanges, formatting);
  534. Paragraph firstPar = HelperFunctions.GetFirstParagraphEffectedByInsert(Document, index);
  535. if (firstPar != null)
  536. {
  537. XElement[] splitParagraph = HelperFunctions.SplitParagraph(firstPar, index - firstPar.startIndex);
  538. firstPar.Xml.ReplaceWith
  539. (
  540. splitParagraph[0],
  541. newParagraph.Xml,
  542. splitParagraph[1]
  543. );
  544. }
  545. else
  546. Xml.Add(newParagraph);
  547. GetParent(newParagraph);
  548. return newParagraph;
  549. }
  550. private ContainerType GetParentFromXmlName(string xmlName)
  551. {
  552. ContainerType parent;
  553. switch (xmlName)
  554. {
  555. case "body":
  556. parent = ContainerType.Body;
  557. break;
  558. case "p":
  559. parent = ContainerType.Paragraph;
  560. break;
  561. case "tbl":
  562. parent = ContainerType.Table;
  563. break;
  564. case "sectPr":
  565. parent = ContainerType.Section;
  566. break;
  567. case "tc":
  568. parent = ContainerType.Cell;
  569. break;
  570. default:
  571. parent = ContainerType.None;
  572. break;
  573. }
  574. return parent;
  575. }
  576. private void GetParent(Paragraph newParagraph)
  577. {
  578. var containerType = GetType();
  579. switch (containerType.Name)
  580. {
  581. case "Body":
  582. newParagraph.ParentContainer = ContainerType.Body;
  583. break;
  584. case "Table":
  585. newParagraph.ParentContainer = ContainerType.Table;
  586. break;
  587. case "TOC":
  588. newParagraph.ParentContainer = ContainerType.TOC;
  589. break;
  590. case "Section":
  591. newParagraph.ParentContainer = ContainerType.Section;
  592. break;
  593. case "Cell":
  594. newParagraph.ParentContainer = ContainerType.Cell;
  595. break;
  596. case "Header":
  597. newParagraph.ParentContainer = ContainerType.Header;
  598. break;
  599. case "Footer":
  600. newParagraph.ParentContainer = ContainerType.Footer;
  601. break;
  602. case "Paragraph":
  603. newParagraph.ParentContainer = ContainerType.Paragraph;
  604. break;
  605. }
  606. }
  607. private ListItemType GetListItemType(string styleName)
  608. {
  609. ListItemType listItemType;
  610. switch (styleName)
  611. {
  612. case "bullet":
  613. listItemType = ListItemType.Bulleted;
  614. break;
  615. default:
  616. listItemType = ListItemType.Numbered;
  617. break;
  618. }
  619. return listItemType;
  620. }
  621. public virtual void InsertSection()
  622. {
  623. InsertSection(false);
  624. }
  625. public virtual void InsertSection(bool trackChanges)
  626. {
  627. var newParagraphSection = new XElement
  628. (
  629. XName.Get("p", DocX.w.NamespaceName), new XElement(XName.Get("pPr", DocX.w.NamespaceName), new XElement(XName.Get("sectPr", DocX.w.NamespaceName), new XElement(XName.Get("type", DocX.w.NamespaceName), new XAttribute(DocX.w + "val", "continuous"))))
  630. );
  631. if (trackChanges)
  632. newParagraphSection = HelperFunctions.CreateEdit(EditType.ins, DateTime.Now, newParagraphSection);
  633. Xml.Add(newParagraphSection);
  634. }
  635. public virtual void InsertSectionPageBreak(bool trackChanges = false)
  636. {
  637. var newParagraphSection = new XElement
  638. (
  639. XName.Get("p", DocX.w.NamespaceName), new XElement(XName.Get("pPr", DocX.w.NamespaceName), new XElement(XName.Get("sectPr", DocX.w.NamespaceName)))
  640. );
  641. if (trackChanges)
  642. newParagraphSection = HelperFunctions.CreateEdit(EditType.ins, DateTime.Now, newParagraphSection);
  643. Xml.Add(newParagraphSection);
  644. }
  645. public virtual Paragraph InsertParagraph(string text)
  646. {
  647. return InsertParagraph(text, false, new Formatting());
  648. }
  649. public virtual Paragraph InsertParagraph(string text, bool trackChanges)
  650. {
  651. return InsertParagraph(text, trackChanges, new Formatting());
  652. }
  653. public virtual Paragraph InsertParagraph(string text, bool trackChanges, Formatting formatting)
  654. {
  655. XElement newParagraph = new XElement
  656. (
  657. XName.Get("p", DocX.w.NamespaceName), new XElement(XName.Get("pPr", DocX.w.NamespaceName)), HelperFunctions.FormatInput(text, formatting.Xml)
  658. );
  659. if (trackChanges)
  660. newParagraph = HelperFunctions.CreateEdit(EditType.ins, DateTime.Now, newParagraph);
  661. Xml.Add(newParagraph);
  662. var paragraphAdded = new Paragraph(Document, newParagraph, 0);
  663. if (this is Cell)
  664. {
  665. var cell = this as Cell;
  666. paragraphAdded.PackagePart = cell.mainPart;
  667. }
  668. else if (this is DocX)
  669. {
  670. paragraphAdded.PackagePart = Document.mainPart;
  671. }
  672. else if (this is Footer)
  673. {
  674. var f = this as Footer;
  675. paragraphAdded.mainPart = f.mainPart;
  676. }
  677. else if (this is Header)
  678. {
  679. var h = this as Header;
  680. paragraphAdded.mainPart = h.mainPart;
  681. }
  682. else
  683. {
  684. Console.WriteLine("No idea what we are {0}", this);
  685. paragraphAdded.PackagePart = Document.mainPart;
  686. }
  687. GetParent(paragraphAdded);
  688. return paragraphAdded;
  689. }
  690. public virtual Paragraph InsertEquation(string equation)
  691. {
  692. Paragraph p = InsertParagraph();
  693. p.AppendEquation(equation);
  694. return p;
  695. }
  696. public virtual Paragraph InsertBookmark(String bookmarkName)
  697. {
  698. var p = InsertParagraph();
  699. p.AppendBookmark(bookmarkName);
  700. return p;
  701. }
  702. public virtual Table InsertTable(int rowCount, int columnCount) //Dmitchern, changed to virtual, and overrided in Table.Cell
  703. {
  704. XElement newTable = HelperFunctions.CreateTable(rowCount, columnCount);
  705. Xml.Add(newTable);
  706. return new Table(Document, newTable) { mainPart = mainPart};
  707. }
  708. public Table InsertTable(int index, int rowCount, int columnCount)
  709. {
  710. XElement newTable = HelperFunctions.CreateTable(rowCount, columnCount);
  711. Paragraph p = HelperFunctions.GetFirstParagraphEffectedByInsert(Document, index);
  712. if (p == null)
  713. Xml.Elements().First().AddFirst(newTable);
  714. else
  715. {
  716. XElement[] split = HelperFunctions.SplitParagraph(p, index - p.startIndex);
  717. p.Xml.ReplaceWith
  718. (
  719. split[0],
  720. newTable,
  721. split[1]
  722. );
  723. }
  724. return new Table(Document, newTable) { mainPart = mainPart };
  725. }
  726. public Table InsertTable(Table t)
  727. {
  728. XElement newXElement = new XElement(t.Xml);
  729. Xml.Add(newXElement);
  730. Table newTable = new Table(Document, newXElement)
  731. {
  732. mainPart = mainPart,
  733. Design = t.Design
  734. };
  735. return newTable;
  736. }
  737. public Table InsertTable(int index, Table t)
  738. {
  739. Paragraph p = HelperFunctions.GetFirstParagraphEffectedByInsert(Document, index);
  740. XElement[] split = HelperFunctions.SplitParagraph(p, index - p.startIndex);
  741. XElement newXElement = new XElement(t.Xml);
  742. p.Xml.ReplaceWith
  743. (
  744. split[0],
  745. newXElement,
  746. split[1]
  747. );
  748. Table newTable = new Table(Document, newXElement)
  749. {
  750. mainPart = mainPart,
  751. Design = t.Design
  752. };
  753. return newTable;
  754. }
  755. internal Container(DocX document, XElement xml)
  756. : base(document, xml)
  757. {
  758. }
  759. public List InsertList(List list)
  760. {
  761. foreach (var item in list.Items)
  762. {
  763. // item.Font(System.Drawing.FontFamily fontFamily)
  764. Xml.Add(item.Xml);
  765. }
  766. return list;
  767. }
  768. public List InsertList(List list, double fontSize)
  769. {
  770. foreach (var item in list.Items)
  771. {
  772. item.FontSize(fontSize);
  773. Xml.Add(item.Xml);
  774. }
  775. return list;
  776. }
  777. public List InsertList(List list, System.Drawing.FontFamily fontFamily, double fontSize)
  778. {
  779. foreach (var item in list.Items)
  780. {
  781. item.Font(fontFamily);
  782. item.FontSize(fontSize);
  783. Xml.Add(item.Xml);
  784. }
  785. return list;
  786. }
  787. public List InsertList(int index, List list)
  788. {
  789. Paragraph p = HelperFunctions.GetFirstParagraphEffectedByInsert(Document, index);
  790. XElement[] split = HelperFunctions.SplitParagraph(p, index - p.startIndex);
  791. var elements = new List<XElement> { split[0] };
  792. elements.AddRange(list.Items.Select(i => new XElement(i.Xml)));
  793. elements.Add(split[1]);
  794. p.Xml.ReplaceWith(elements.ToArray());
  795. return list;
  796. }
  797. }
  798. }