您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

Container.cs 36KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994
  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 searchValue, string newValue, bool trackChanges = false, RegexOptions options = RegexOptions.None, Formatting newFormatting = null, Formatting matchFormatting = null, MatchFormattingOptions formattingOptions = MatchFormattingOptions.SubsetMatch, bool escapeRegEx = true, bool useRegExSubstitutions = false)
  362. {
  363. if (string.IsNullOrEmpty(searchValue))
  364. throw new ArgumentException("oldValue cannot be null or empty", "searchValue");
  365. if (newValue == null)
  366. throw new ArgumentException("newValue cannot be null or empty", "newValue");
  367. // ReplaceText in Headers of the document.
  368. var headerList = new List<Header> { Document.Headers.first, Document.Headers.even, Document.Headers.odd };
  369. foreach (var header in headerList)
  370. if (header != null)
  371. foreach (var paragraph in header.Paragraphs)
  372. paragraph.ReplaceText(searchValue, newValue, trackChanges, options, newFormatting, matchFormatting, formattingOptions, escapeRegEx, useRegExSubstitutions);
  373. // ReplaceText int main body of document.
  374. foreach (var paragraph in Paragraphs)
  375. paragraph.ReplaceText(searchValue, newValue, trackChanges, options, newFormatting, matchFormatting, formattingOptions, escapeRegEx, useRegExSubstitutions);
  376. // ReplaceText in Footers of the document.
  377. var footerList = new List<Footer> { Document.Footers.first, Document.Footers.even, Document.Footers.odd };
  378. foreach (var footer in footerList)
  379. if (footer != null)
  380. foreach (var paragraph in footer.Paragraphs)
  381. paragraph.ReplaceText(searchValue, newValue, trackChanges, options, newFormatting, matchFormatting, formattingOptions, escapeRegEx, useRegExSubstitutions);
  382. }
  383. /// <summary>
  384. ///
  385. /// </summary>
  386. /// <param name="searchValue">Value to find</param>
  387. /// <param name="regexMatchHandler">A Func that accepts the matching regex search group value and passes it to this to return the replacement string</param>
  388. /// <param name="trackChanges">Enable trackchanges</param>
  389. /// <param name="options">Regex options</param>
  390. /// <param name="newFormatting"></param>
  391. /// <param name="matchFormatting"></param>
  392. /// <param name="formattingOptions"></param>
  393. public virtual void ReplaceText(string searchValue, Func<string,string> regexMatchHandler, bool trackChanges = false, RegexOptions options = RegexOptions.None, Formatting newFormatting = null, Formatting matchFormatting = null, MatchFormattingOptions formattingOptions = MatchFormattingOptions.SubsetMatch)
  394. {
  395. if (string.IsNullOrEmpty(searchValue))
  396. throw new ArgumentException("oldValue cannot be null or empty", "searchValue");
  397. if (regexMatchHandler == null)
  398. throw new ArgumentException("regexMatchHandler cannot be null", "regexMatchHandler");
  399. // ReplaceText in Headers/Footers of the document.
  400. var containerList = new List<IParagraphContainer> {
  401. Document.Headers.first, Document.Headers.even, Document.Headers.odd,
  402. Document.Footers.first, Document.Footers.even, Document.Footers.odd };
  403. foreach (var container in containerList)
  404. if (container != null)
  405. foreach (var paragraph in container.Paragraphs)
  406. paragraph.ReplaceText(searchValue, regexMatchHandler, trackChanges, options, newFormatting, matchFormatting, formattingOptions);
  407. // ReplaceText int main body of document.
  408. foreach (var paragraph in Paragraphs)
  409. paragraph.ReplaceText(searchValue, regexMatchHandler, trackChanges, options, newFormatting, matchFormatting, formattingOptions);
  410. }
  411. /// <summary>
  412. /// Removes all items with required formatting
  413. /// </summary>
  414. /// <returns>Numer of texts removed</returns>
  415. public int RemoveTextInGivenFormat(Formatting matchFormatting, MatchFormattingOptions fo = MatchFormattingOptions.SubsetMatch)
  416. {
  417. var deletedCount = 0;
  418. foreach (var x in Xml.Elements())
  419. {
  420. deletedCount += RemoveTextWithFormatRecursive(x, matchFormatting, fo);
  421. }
  422. return deletedCount;
  423. }
  424. internal int RemoveTextWithFormatRecursive(XElement element, Formatting matchFormatting, MatchFormattingOptions fo)
  425. {
  426. var deletedCount = 0;
  427. foreach (var x in element.Elements())
  428. {
  429. if ("rPr".Equals(x.Name.LocalName))
  430. {
  431. if (HelperFunctions.ContainsEveryChildOf(matchFormatting.Xml, x, fo))
  432. {
  433. x.Parent.Remove();
  434. ++deletedCount;
  435. }
  436. }
  437. deletedCount += RemoveTextWithFormatRecursive(x, matchFormatting, fo);
  438. }
  439. return deletedCount;
  440. }
  441. public virtual void InsertAtBookmark(string toInsert, string bookmarkName)
  442. {
  443. if (bookmarkName.IsNullOrWhiteSpace())
  444. throw new ArgumentException("bookmark cannot be null or empty", "bookmarkName");
  445. var headerCollection = Document.Headers;
  446. var headers = new List<Header> { headerCollection.first, headerCollection.even, headerCollection.odd };
  447. foreach (var header in headers.Where(x => x != null))
  448. foreach (var paragraph in header.Paragraphs)
  449. paragraph.InsertAtBookmark(toInsert, bookmarkName);
  450. foreach (var paragraph in Paragraphs)
  451. paragraph.InsertAtBookmark(toInsert, bookmarkName);
  452. var footerCollection = Document.Footers;
  453. var footers = new List<Footer> { footerCollection.first, footerCollection.even, footerCollection.odd };
  454. foreach (var footer in footers.Where(x => x != null))
  455. foreach (var paragraph in footer.Paragraphs)
  456. paragraph.InsertAtBookmark(toInsert, bookmarkName);
  457. }
  458. public string[] ValidateBookmarks(params string[] bookmarkNames)
  459. {
  460. var headers = new[] {Document.Headers.first, Document.Headers.even, Document.Headers.odd}.Where(h => h != null).ToList();
  461. var footers = new[] {Document.Footers.first, Document.Footers.even, Document.Footers.odd}.Where(f => f != null).ToList();
  462. var nonMatching = new List<string>();
  463. foreach (var bookmarkName in bookmarkNames)
  464. {
  465. if (headers.SelectMany(h => h.Paragraphs).Any(p => p.ValidateBookmark(bookmarkName))) return new string[0];
  466. if (footers.SelectMany(h => h.Paragraphs).Any(p => p.ValidateBookmark(bookmarkName))) return new string[0];
  467. if (Paragraphs.Any(p => p.ValidateBookmark(bookmarkName))) return new string[0];
  468. nonMatching.Add(bookmarkName);
  469. }
  470. return nonMatching.ToArray();
  471. }
  472. public virtual Paragraph InsertParagraph(int index, string text, bool trackChanges)
  473. {
  474. return InsertParagraph(index, text, trackChanges, null);
  475. }
  476. public virtual Paragraph InsertParagraph()
  477. {
  478. return InsertParagraph(string.Empty, false);
  479. }
  480. public virtual Paragraph InsertParagraph(int index, Paragraph p)
  481. {
  482. XElement newXElement = new XElement(p.Xml);
  483. p.Xml = newXElement;
  484. Paragraph paragraph = HelperFunctions.GetFirstParagraphEffectedByInsert(Document, index);
  485. if (paragraph == null)
  486. Xml.Add(p.Xml);
  487. else
  488. {
  489. XElement[] split = HelperFunctions.SplitParagraph(paragraph, index - paragraph.startIndex);
  490. paragraph.Xml.ReplaceWith
  491. (
  492. split[0],
  493. newXElement,
  494. split[1]
  495. );
  496. }
  497. GetParent(p);
  498. return p;
  499. }
  500. public virtual Paragraph InsertParagraph(Paragraph p)
  501. {
  502. #region Styles
  503. XDocument style_document;
  504. if (p.styles.Count() > 0)
  505. {
  506. Uri style_package_uri = new Uri("/word/styles.xml", UriKind.Relative);
  507. if (!Document.package.PartExists(style_package_uri))
  508. {
  509. PackagePart style_package = Document.package.CreatePart(style_package_uri, "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml", CompressionOption.Maximum);
  510. using (TextWriter tw = new StreamWriter(style_package.GetStream()))
  511. {
  512. style_document = new XDocument
  513. (
  514. new XDeclaration("1.0", "UTF-8", "yes"),
  515. new XElement(XName.Get("styles", DocX.w.NamespaceName))
  516. );
  517. style_document.Save(tw);
  518. }
  519. }
  520. PackagePart styles_document = Document.package.GetPart(style_package_uri);
  521. using (TextReader tr = new StreamReader(styles_document.GetStream()))
  522. {
  523. style_document = XDocument.Load(tr);
  524. XElement styles_element = style_document.Element(XName.Get("styles", DocX.w.NamespaceName));
  525. var ids = from d in styles_element.Descendants(XName.Get("style", DocX.w.NamespaceName))
  526. let a = d.Attribute(XName.Get("styleId", DocX.w.NamespaceName))
  527. where a != null
  528. select a.Value;
  529. foreach (XElement style in p.styles)
  530. {
  531. // If styles_element does not contain this element, then add it.
  532. if (!ids.Contains(style.Attribute(XName.Get("styleId", DocX.w.NamespaceName)).Value))
  533. styles_element.Add(style);
  534. }
  535. }
  536. using (TextWriter tw = new StreamWriter(styles_document.GetStream()))
  537. style_document.Save(tw);
  538. }
  539. #endregion
  540. XElement newXElement = new XElement(p.Xml);
  541. Xml.Add(newXElement);
  542. int index = 0;
  543. if (Document.paragraphLookup.Keys.Count() > 0)
  544. {
  545. index = Document.paragraphLookup.Last().Key;
  546. if (Document.paragraphLookup.Last().Value.Text.Length == 0)
  547. index++;
  548. else
  549. index += Document.paragraphLookup.Last().Value.Text.Length;
  550. }
  551. Paragraph newParagraph = new Paragraph(Document, newXElement, index);
  552. Document.paragraphLookup.Add(index, newParagraph);
  553. GetParent(newParagraph);
  554. return newParagraph;
  555. }
  556. public virtual Paragraph InsertParagraph(int index, string text, bool trackChanges, Formatting formatting)
  557. {
  558. Paragraph newParagraph = new Paragraph(Document, new XElement(DocX.w + "p"), index);
  559. newParagraph.InsertText(0, text, trackChanges, formatting);
  560. Paragraph firstPar = HelperFunctions.GetFirstParagraphEffectedByInsert(Document, index);
  561. if (firstPar != null)
  562. {
  563. var splitindex = index - firstPar.startIndex;
  564. if (splitindex <= 0)
  565. {
  566. firstPar.Xml.ReplaceWith(newParagraph.Xml, firstPar.Xml);
  567. }
  568. else {
  569. XElement[] splitParagraph = HelperFunctions.SplitParagraph(firstPar, splitindex);
  570. firstPar.Xml.ReplaceWith
  571. (
  572. splitParagraph[0],
  573. newParagraph.Xml,
  574. splitParagraph[1]
  575. );
  576. }
  577. }
  578. else
  579. Xml.Add(newParagraph);
  580. GetParent(newParagraph);
  581. return newParagraph;
  582. }
  583. private ContainerType GetParentFromXmlName(string xmlName)
  584. {
  585. ContainerType parent;
  586. switch (xmlName)
  587. {
  588. case "body":
  589. parent = ContainerType.Body;
  590. break;
  591. case "p":
  592. parent = ContainerType.Paragraph;
  593. break;
  594. case "tbl":
  595. parent = ContainerType.Table;
  596. break;
  597. case "sectPr":
  598. parent = ContainerType.Section;
  599. break;
  600. case "tc":
  601. parent = ContainerType.Cell;
  602. break;
  603. default:
  604. parent = ContainerType.None;
  605. break;
  606. }
  607. return parent;
  608. }
  609. private void GetParent(Paragraph newParagraph)
  610. {
  611. var containerType = GetType();
  612. switch (containerType.Name)
  613. {
  614. case "Body":
  615. newParagraph.ParentContainer = ContainerType.Body;
  616. break;
  617. case "Table":
  618. newParagraph.ParentContainer = ContainerType.Table;
  619. break;
  620. case "TOC":
  621. newParagraph.ParentContainer = ContainerType.TOC;
  622. break;
  623. case "Section":
  624. newParagraph.ParentContainer = ContainerType.Section;
  625. break;
  626. case "Cell":
  627. newParagraph.ParentContainer = ContainerType.Cell;
  628. break;
  629. case "Header":
  630. newParagraph.ParentContainer = ContainerType.Header;
  631. break;
  632. case "Footer":
  633. newParagraph.ParentContainer = ContainerType.Footer;
  634. break;
  635. case "Paragraph":
  636. newParagraph.ParentContainer = ContainerType.Paragraph;
  637. break;
  638. }
  639. }
  640. private ListItemType GetListItemType(string styleName)
  641. {
  642. ListItemType listItemType;
  643. switch (styleName)
  644. {
  645. case "bullet":
  646. listItemType = ListItemType.Bulleted;
  647. break;
  648. default:
  649. listItemType = ListItemType.Numbered;
  650. break;
  651. }
  652. return listItemType;
  653. }
  654. public virtual void InsertSection()
  655. {
  656. InsertSection(false);
  657. }
  658. public virtual void InsertSection(bool trackChanges)
  659. {
  660. var newParagraphSection = new XElement
  661. (
  662. 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"))))
  663. );
  664. if (trackChanges)
  665. newParagraphSection = HelperFunctions.CreateEdit(EditType.ins, DateTime.Now, newParagraphSection);
  666. Xml.Add(newParagraphSection);
  667. }
  668. public virtual void InsertSectionPageBreak(bool trackChanges = false)
  669. {
  670. var newParagraphSection = new XElement
  671. (
  672. XName.Get("p", DocX.w.NamespaceName), new XElement(XName.Get("pPr", DocX.w.NamespaceName), new XElement(XName.Get("sectPr", DocX.w.NamespaceName)))
  673. );
  674. if (trackChanges)
  675. newParagraphSection = HelperFunctions.CreateEdit(EditType.ins, DateTime.Now, newParagraphSection);
  676. Xml.Add(newParagraphSection);
  677. }
  678. public virtual Paragraph InsertParagraph(string text)
  679. {
  680. return InsertParagraph(text, false, new Formatting());
  681. }
  682. public virtual Paragraph InsertParagraph(string text, bool trackChanges)
  683. {
  684. return InsertParagraph(text, trackChanges, new Formatting());
  685. }
  686. public virtual Paragraph InsertParagraph(string text, bool trackChanges, Formatting formatting)
  687. {
  688. XElement newParagraph = new XElement
  689. (
  690. XName.Get("p", DocX.w.NamespaceName), new XElement(XName.Get("pPr", DocX.w.NamespaceName)), HelperFunctions.FormatInput(text, formatting.Xml)
  691. );
  692. if (trackChanges)
  693. newParagraph = HelperFunctions.CreateEdit(EditType.ins, DateTime.Now, newParagraph);
  694. Xml.Add(newParagraph);
  695. var paragraphAdded = new Paragraph(Document, newParagraph, 0);
  696. if (this is Cell)
  697. {
  698. var cell = this as Cell;
  699. paragraphAdded.PackagePart = cell.mainPart;
  700. }
  701. else if (this is DocX)
  702. {
  703. paragraphAdded.PackagePart = Document.mainPart;
  704. }
  705. else if (this is Footer)
  706. {
  707. var f = this as Footer;
  708. paragraphAdded.mainPart = f.mainPart;
  709. }
  710. else if (this is Header)
  711. {
  712. var h = this as Header;
  713. paragraphAdded.mainPart = h.mainPart;
  714. }
  715. else
  716. {
  717. Console.WriteLine("No idea what we are {0}", this);
  718. paragraphAdded.PackagePart = Document.mainPart;
  719. }
  720. GetParent(paragraphAdded);
  721. return paragraphAdded;
  722. }
  723. public virtual Paragraph InsertEquation(string equation)
  724. {
  725. Paragraph p = InsertParagraph();
  726. p.AppendEquation(equation);
  727. return p;
  728. }
  729. public virtual Paragraph InsertBookmark(String bookmarkName)
  730. {
  731. var p = InsertParagraph();
  732. p.AppendBookmark(bookmarkName);
  733. return p;
  734. }
  735. public virtual Table InsertTable(int rowCount, int columnCount) //Dmitchern, changed to virtual, and overrided in Table.Cell
  736. {
  737. XElement newTable = HelperFunctions.CreateTable(rowCount, columnCount);
  738. Xml.Add(newTable);
  739. return new Table(Document, newTable) { mainPart = mainPart};
  740. }
  741. public Table InsertTable(int index, int rowCount, int columnCount)
  742. {
  743. XElement newTable = HelperFunctions.CreateTable(rowCount, columnCount);
  744. Paragraph p = HelperFunctions.GetFirstParagraphEffectedByInsert(Document, index);
  745. if (p == null)
  746. Xml.Elements().First().AddFirst(newTable);
  747. else
  748. {
  749. XElement[] split = HelperFunctions.SplitParagraph(p, index - p.startIndex);
  750. p.Xml.ReplaceWith
  751. (
  752. split[0],
  753. newTable,
  754. split[1]
  755. );
  756. }
  757. return new Table(Document, newTable) { mainPart = mainPart };
  758. }
  759. public Table InsertTable(Table t)
  760. {
  761. XElement newXElement = new XElement(t.Xml);
  762. Xml.Add(newXElement);
  763. Table newTable = new Table(Document, newXElement)
  764. {
  765. mainPart = mainPart,
  766. Design = t.Design
  767. };
  768. return newTable;
  769. }
  770. public Table InsertTable(int index, Table t)
  771. {
  772. Paragraph p = HelperFunctions.GetFirstParagraphEffectedByInsert(Document, index);
  773. XElement[] split = HelperFunctions.SplitParagraph(p, index - p.startIndex);
  774. XElement newXElement = new XElement(t.Xml);
  775. p.Xml.ReplaceWith
  776. (
  777. split[0],
  778. newXElement,
  779. split[1]
  780. );
  781. Table newTable = new Table(Document, newXElement)
  782. {
  783. mainPart = mainPart,
  784. Design = t.Design
  785. };
  786. return newTable;
  787. }
  788. internal Container(DocX document, XElement xml)
  789. : base(document, xml)
  790. {
  791. }
  792. public List InsertList(List list)
  793. {
  794. foreach (var item in list.Items)
  795. {
  796. Xml.Add(item.Xml);
  797. }
  798. return list;
  799. }
  800. public List InsertList(List list, double fontSize)
  801. {
  802. foreach (var item in list.Items)
  803. {
  804. item.FontSize(fontSize);
  805. Xml.Add(item.Xml);
  806. }
  807. return list;
  808. }
  809. public List InsertList(List list, System.Drawing.FontFamily fontFamily, double fontSize)
  810. {
  811. foreach (var item in list.Items)
  812. {
  813. item.Font(fontFamily);
  814. item.FontSize(fontSize);
  815. Xml.Add(item.Xml);
  816. }
  817. return list;
  818. }
  819. public List InsertList(int index, List list)
  820. {
  821. Paragraph p = HelperFunctions.GetFirstParagraphEffectedByInsert(Document, index);
  822. XElement[] split = HelperFunctions.SplitParagraph(p, index - p.startIndex);
  823. var elements = new List<XElement> { split[0] };
  824. elements.AddRange(list.Items.Select(i => new XElement(i.Xml)));
  825. elements.Add(split[1]);
  826. p.Xml.ReplaceWith(elements.ToArray());
  827. return list;
  828. }
  829. }
  830. }