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 31KB

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