Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

Container.cs 31KB

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