-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathContainer.cs
More file actions
1047 lines (876 loc) · 37.5 KB
/
Container.cs
File metadata and controls
1047 lines (876 loc) · 37.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.IO;
using System.Linq;
using System.Xml.Linq;
using System.IO.Packaging;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Collections.ObjectModel;
namespace Novacode
{
public abstract class Container : DocXElement
{
public virtual ReadOnlyCollection<Content> Contents
{
get
{
List<Content> contents = GetContents();
return contents.AsReadOnly();
}
}
/// <summary>
/// Returns a list of all Paragraphs inside this container.
/// </summary>
/// <example>
/// <code>
/// Load a document.
/// using (DocX document = DocX.Load(@"Test.docx"))
/// {
/// // All Paragraphs in this document.
/// <![CDATA[ List<Paragraph> ]]> documentParagraphs = document.Paragraphs;
///
/// // Make sure this document contains at least one Table.
/// if (document.Tables.Count() > 0)
/// {
/// // Get the first Table in this document.
/// Table t = document.Tables[0];
///
/// // All Paragraphs in this Table.
/// <![CDATA[ List<Paragraph> ]]> tableParagraphs = t.Paragraphs;
///
/// // Make sure this Table contains at least one Row.
/// if (t.Rows.Count() > 0)
/// {
/// // Get the first Row in this document.
/// Row r = t.Rows[0];
///
/// // All Paragraphs in this Row.
/// <![CDATA[ List<Paragraph> ]]> rowParagraphs = r.Paragraphs;
///
/// // Make sure this Row contains at least one Cell.
/// if (r.Cells.Count() > 0)
/// {
/// // Get the first Cell in this document.
/// Cell c = r.Cells[0];
///
/// // All Paragraphs in this Cell.
/// <![CDATA[ List<Paragraph> ]]> cellParagraphs = c.Paragraphs;
/// }
/// }
/// }
///
/// // Save all changes to this document.
/// document.Save();
/// }// Release this document from memory.
/// </code>
/// </example>
public virtual ReadOnlyCollection<Paragraph> Paragraphs
{
get
{
List<Paragraph> paragraphs = GetParagraphs();
foreach (var p in paragraphs)
{
if ((p.Xml.ElementsAfterSelf().FirstOrDefault() != null) && (p.Xml.ElementsAfterSelf().First().Name.Equals(DocX.w + "tbl")))
p.FollowingTable = new Table(this.Document, p.Xml.ElementsAfterSelf().First());
p.ParentContainer = GetParentFromXmlName(p.Xml.Ancestors().First().Name.LocalName);
if (p.IsListItem)
{
GetListItemType(p);
}
}
return paragraphs.AsReadOnly();
}
}
public virtual ReadOnlyCollection<Paragraph> ParagraphsDeepSearch
{
get
{
List<Paragraph> paragraphs = GetParagraphs(true);
foreach (var p in paragraphs)
{
if ((p.Xml.ElementsAfterSelf().FirstOrDefault() != null) && (p.Xml.ElementsAfterSelf().First().Name.Equals(DocX.w + "tbl")))
p.FollowingTable = new Table(this.Document, p.Xml.ElementsAfterSelf().First());
p.ParentContainer = GetParentFromXmlName(p.Xml.Ancestors().First().Name.LocalName);
if (p.IsListItem)
{
GetListItemType(p);
}
}
return paragraphs.AsReadOnly();
}
}
/// <summary>
/// Removes paragraph at specified position
/// </summary>
/// <param name="index">Index of paragraph to remove</param>
/// <returns>True if removed</returns>
public bool RemoveParagraphAt(int index)
{
int i = 0;
foreach (var paragraph in Xml.Descendants(DocX.w + "p"))
{
if (i == index)
{
paragraph.Remove();
return true;
}
++i;
}
return false;
}
/// <summary>
/// Removes paragraph
/// </summary>
/// <param name="p">Paragraph to remove</param>
/// <returns>True if removed</returns>
public bool RemoveParagraph(Paragraph p)
{
foreach (var paragraph in Xml.Descendants(DocX.w + "p"))
{
if (paragraph.Equals(p.Xml))
{
paragraph.Remove();
return true;
}
}
return false;
}
public virtual List<Section> Sections
{
get
{
var allParas = Paragraphs;
var parasInASection = new List<Paragraph>();
var sections = new List<Section>();
foreach (var para in allParas)
{
var sectionInPara = para.Xml.Descendants().FirstOrDefault(s => s.Name.LocalName == "sectPr");
if (sectionInPara == null)
{
parasInASection.Add(para);
}
else
{
parasInASection.Add(para);
var section = new Section(Document, sectionInPara) { SectionParagraphs = parasInASection };
sections.Add(section);
parasInASection = new List<Paragraph>();
}
}
XElement body = Xml.Element(XName.Get("body", DocX.w.NamespaceName));
if (body != null)
{
XElement baseSectionXml = body.Element(XName.Get("sectPr", DocX.w.NamespaceName));
var baseSection = new Section(Document, baseSectionXml) { SectionParagraphs = parasInASection };
sections.Add(baseSection);
}
return sections;
}
}
private void GetListItemType(Paragraph p)
{
var ilvlNode = p.ParagraphNumberProperties.Descendants().FirstOrDefault(el => el.Name.LocalName == "ilvl");
var ilvlValue = ilvlNode.Attribute(DocX.w + "val").Value;
var numIdNode = p.ParagraphNumberProperties.Descendants().FirstOrDefault(el => el.Name.LocalName == "numId");
var numIdValue = numIdNode.Attribute(DocX.w + "val").Value;
//find num node in numbering
var numNodes = Document.numbering.Descendants().Where(n => n.Name.LocalName == "num");
XElement numNode = numNodes.FirstOrDefault(node => node.Attribute(DocX.w + "numId").Value.Equals(numIdValue));
if (numNode != null)
{
//Get abstractNumId node and its value from numNode
var abstractNumIdNode = numNode.Descendants().First(n => n.Name.LocalName == "abstractNumId");
var abstractNumNodeValue = abstractNumIdNode.Attribute(DocX.w + "val").Value;
var abstractNumNodes = Document.numbering.Descendants().Where(n => n.Name.LocalName == "abstractNum");
XElement abstractNumNode =
abstractNumNodes.FirstOrDefault(node => node.Attribute(DocX.w + "abstractNumId").Value.Equals(abstractNumNodeValue));
//Find lvl node
var lvlNodes = abstractNumNode.Descendants().Where(n => n.Name.LocalName == "lvl");
XElement lvlNode = null;
foreach (XElement node in lvlNodes)
{
if (node.Attribute(DocX.w + "ilvl").Value.Equals(ilvlValue))
{
lvlNode = node;
break;
}
}
var numFmtNode = lvlNode.Descendants().First(n => n.Name.LocalName == "numFmt");
p.ListItemType = GetListItemType(numFmtNode.Attribute(DocX.w + "val").Value);
}
}
public ContainerType ParentContainer;
internal List<Content> GetContents(bool deepSearch = false)
{
// Need some memory that can be updated by the recursive search.
//int index = 0;
List<Content> contents = new List<Content>();
foreach (XElement e in Xml.Descendants(XName.Get("sdt", DocX.w.NamespaceName)))
{
Content content = new Content(Document, e, 0);
XElement el = e.Elements(XName.Get("sdtPr", DocX.w.NamespaceName)).First();
content.Name = GetAttribute(el, "alias", "val");
content.Tag = GetAttribute(el, "tag", "val");
contents.Add(content);
}
return contents;
}
private string GetAttribute(XElement e, string localName, string attributeName)
{
string val = string.Empty;
try
{
val = e.Elements(XName.Get(localName, DocX.w.NamespaceName)).Attributes(XName.Get(attributeName, DocX.w.NamespaceName)).FirstOrDefault().Value;
}
catch (Exception)
{
val = "Missing";
}
return val;
}
internal List<Paragraph> GetParagraphs(bool deepSearch = false)
{
// Need some memory that can be updated by the recursive search.
int index = 0;
List<Paragraph> paragraphs = new List<Paragraph>();
foreach (XElement e in Xml.Descendants(XName.Get("p", DocX.w.NamespaceName)))
{
Paragraph paragraph = new Paragraph(Document, e, index);
paragraphs.Add(paragraph);
index += HelperFunctions.GetText(e).Length;
}
// GetParagraphsRecursive(Xml, ref index, ref paragraphs, deepSearch);
return paragraphs;
}
internal void GetParagraphsRecursive(XElement Xml, ref int index, ref List<Paragraph> paragraphs, bool deepSearch = false)
{
// sdtContent are for PageNumbers inside Headers or Footers, don't go any deeper.
//if (Xml.Name.LocalName == "sdtContent")
// return;
var keepSearching = true;
if (Xml.Name.LocalName == "p")
{
paragraphs.Add(new Paragraph(Document, Xml, index));
index += HelperFunctions.GetText(Xml).Length;
if (!deepSearch)
keepSearching = false;
}
if (keepSearching && Xml.HasElements)
{
foreach (XElement e in Xml.Elements())
{
GetParagraphsRecursive(e, ref index, ref paragraphs, deepSearch);
}
}
}
public virtual List<Table> Tables
{
get
{
List<Table> tables =
(
from t in Xml.Descendants(DocX.w + "tbl")
select new Table(Document, t)
).ToList();
return tables;
}
}
public virtual List<List> Lists
{
get
{
var lists = new List<List>();
var list = new List(Document, Xml);
foreach (var paragraph in Paragraphs)
{
if (paragraph.IsListItem)
{
if (list.CanAddListItem(paragraph))
{
list.AddItem(paragraph);
}
else
{
lists.Add(list);
list = new List(Document, Xml);
list.AddItem(paragraph);
}
}
}
lists.Add(list);
return lists;
}
}
public virtual List<Hyperlink> Hyperlinks
{
get
{
List<Hyperlink> hyperlinks = new List<Hyperlink>();
foreach (Paragraph p in Paragraphs)
hyperlinks.AddRange(p.Hyperlinks);
return hyperlinks;
}
}
public virtual List<Picture> Pictures
{
get
{
List<Picture> pictures = new List<Picture>();
foreach (Paragraph p in Paragraphs)
pictures.AddRange(p.Pictures);
return pictures;
}
}
/// <summary>
/// Sets the Direction of content.
/// </summary>
/// <param name="direction">Direction either LeftToRight or RightToLeft</param>
/// <example>
/// Set the Direction of content in a Paragraph to RightToLeft.
/// <code>
/// // Load a document.
/// using (DocX document = DocX.Load(@"Test.docx"))
/// {
/// // Get the first Paragraph from this document.
/// Paragraph p = document.InsertParagraph();
///
/// // Set the Direction of this Paragraph.
/// p.Direction = Direction.RightToLeft;
///
/// // Make sure the document contains at lest one Table.
/// if (document.Tables.Count() > 0)
/// {
/// // Get the first Table from this document.
/// Table t = document.Tables[0];
///
/// /*
/// * Set the direction of the entire Table.
/// * Note: The same function is available at the Row and Cell level.
/// */
/// t.SetDirection(Direction.RightToLeft);
/// }
///
/// // Save all changes to this document.
/// document.Save();
/// }// Release this document from memory.
/// </code>
/// </example>
public virtual void SetDirection(Direction direction)
{
foreach (Paragraph p in Paragraphs)
p.Direction = direction;
}
public virtual List<int> FindAll(string str)
{
return FindAll(str, RegexOptions.None);
}
public virtual List<int> FindAll(string str, RegexOptions options)
{
List<int> list = new List<int>();
foreach (Paragraph p in Paragraphs)
{
List<int> indexes = p.FindAll(str, options);
for (int i = 0; i < indexes.Count(); i++)
indexes[i] += p.startIndex;
list.AddRange(indexes);
}
return list;
}
/// <summary>
/// Find all unique instances of the given Regex Pattern,
/// returning the list of the unique strings found
/// </summary>
/// <param name="pattern"></param>
/// <param name="options"></param>
/// <returns></returns>
public virtual List<string> FindUniqueByPattern(string pattern, RegexOptions options)
{
List<string> rawResults = new List<string>();
foreach (Paragraph p in Paragraphs)
{ // accumulate the search results from all paragraphs
List<string> partials = p.FindAllByPattern(pattern, options);
rawResults.AddRange(partials);
}
// this dictionary is used to collect results and test for uniqueness
Dictionary<string, int> uniqueResults = new Dictionary<string, int>();
foreach (string currValue in rawResults)
{
if (!uniqueResults.ContainsKey(currValue))
{ // if the dictionary doesn't have it, add it
uniqueResults.Add(currValue, 0);
}
}
return uniqueResults.Keys.ToList(); // return the unique list of results
}
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)
{
if (string.IsNullOrEmpty(searchValue))
throw new ArgumentException("oldValue cannot be null or empty", "searchValue");
if (newValue == null)
throw new ArgumentException("newValue cannot be null or empty", "newValue");
// ReplaceText in Headers of the document.
var headerList = new List<Header> { Document.Headers.first, Document.Headers.even, Document.Headers.odd };
foreach (var header in headerList)
if (header != null)
foreach (var paragraph in header.Paragraphs)
paragraph.ReplaceText(searchValue, newValue, trackChanges, options, newFormatting, matchFormatting, formattingOptions, escapeRegEx, useRegExSubstitutions);
// ReplaceText int main body of document.
foreach (var paragraph in Paragraphs)
paragraph.ReplaceText(searchValue, newValue, trackChanges, options, newFormatting, matchFormatting, formattingOptions, escapeRegEx, useRegExSubstitutions);
// ReplaceText in Footers of the document.
var footerList = new List<Footer> { Document.Footers.first, Document.Footers.even, Document.Footers.odd };
foreach (var footer in footerList)
if (footer != null)
foreach (var paragraph in footer.Paragraphs)
paragraph.ReplaceText(searchValue, newValue, trackChanges, options, newFormatting, matchFormatting, formattingOptions, escapeRegEx, useRegExSubstitutions);
}
/// <summary>
///
/// </summary>
/// <param name="searchValue">Value to find</param>
/// <param name="regexMatchHandler">A Func that accepts the matching regex search group value and passes it to this to return the replacement string</param>
/// <param name="trackChanges">Enable trackchanges</param>
/// <param name="options">Regex options</param>
/// <param name="newFormatting"></param>
/// <param name="matchFormatting"></param>
/// <param name="formattingOptions"></param>
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)
{
if (string.IsNullOrEmpty(searchValue))
throw new ArgumentException("oldValue cannot be null or empty", "searchValue");
if (regexMatchHandler == null)
throw new ArgumentException("regexMatchHandler cannot be null", "regexMatchHandler");
// ReplaceText in Headers/Footers of the document.
var containerList = new List<IParagraphContainer> {
Document.Headers.first, Document.Headers.even, Document.Headers.odd,
Document.Footers.first, Document.Footers.even, Document.Footers.odd };
foreach (var container in containerList)
if (container != null)
foreach (var paragraph in container.Paragraphs)
paragraph.ReplaceText(searchValue, regexMatchHandler, trackChanges, options, newFormatting, matchFormatting, formattingOptions);
// ReplaceText int main body of document.
foreach (var paragraph in Paragraphs)
paragraph.ReplaceText(searchValue, regexMatchHandler, trackChanges, options, newFormatting, matchFormatting, formattingOptions);
}
/// <summary>
/// Removes all items with required formatting
/// </summary>
/// <returns>Numer of texts removed</returns>
public int RemoveTextInGivenFormat(Formatting matchFormatting, MatchFormattingOptions fo = MatchFormattingOptions.SubsetMatch)
{
var deletedCount = 0;
foreach (var x in Xml.Elements())
{
deletedCount += RemoveTextWithFormatRecursive(x, matchFormatting, fo);
}
return deletedCount;
}
internal int RemoveTextWithFormatRecursive(XElement element, Formatting matchFormatting, MatchFormattingOptions fo)
{
var deletedCount = 0;
foreach (var x in element.Elements())
{
if ("rPr".Equals(x.Name.LocalName))
{
if (HelperFunctions.ContainsEveryChildOf(matchFormatting.Xml, x, fo))
{
x.Parent.Remove();
++deletedCount;
}
}
deletedCount += RemoveTextWithFormatRecursive(x, matchFormatting, fo);
}
return deletedCount;
}
public virtual void InsertAtBookmark(string toInsert, string bookmarkName)
{
if (bookmarkName.IsNullOrWhiteSpace())
throw new ArgumentException("bookmark cannot be null or empty", "bookmarkName");
var headerCollection = Document.Headers;
var headers = new List<Header> { headerCollection.first, headerCollection.even, headerCollection.odd };
foreach (var header in headers.Where(x => x != null))
foreach (var paragraph in header.Paragraphs)
paragraph.InsertAtBookmark(toInsert, bookmarkName);
foreach (var paragraph in Paragraphs)
paragraph.InsertAtBookmark(toInsert, bookmarkName);
var footerCollection = Document.Footers;
var footers = new List<Footer> { footerCollection.first, footerCollection.even, footerCollection.odd };
foreach (var footer in footers.Where(x => x != null))
foreach (var paragraph in footer.Paragraphs)
paragraph.InsertAtBookmark(toInsert, bookmarkName);
}
public string[] ValidateBookmarks(params string[] bookmarkNames)
{
var headers = new[] { Document.Headers.first, Document.Headers.even, Document.Headers.odd }.Where(h => h != null).ToList();
var footers = new[] { Document.Footers.first, Document.Footers.even, Document.Footers.odd }.Where(f => f != null).ToList();
var nonMatching = new List<string>();
foreach (var bookmarkName in bookmarkNames)
{
if (headers.SelectMany(h => h.Paragraphs).Any(p => p.ValidateBookmark(bookmarkName))) return new string[0];
if (footers.SelectMany(h => h.Paragraphs).Any(p => p.ValidateBookmark(bookmarkName))) return new string[0];
if (Paragraphs.Any(p => p.ValidateBookmark(bookmarkName))) return new string[0];
nonMatching.Add(bookmarkName);
}
return nonMatching.ToArray();
}
public virtual Paragraph InsertParagraph(int index, string text, bool trackChanges)
{
return InsertParagraph(index, text, trackChanges, null);
}
public virtual Paragraph InsertParagraph()
{
return InsertParagraph(string.Empty, false);
}
public virtual Paragraph InsertParagraph(int index, Paragraph p)
{
XElement newXElement = new XElement(p.Xml);
p.Xml = newXElement;
Paragraph paragraph = HelperFunctions.GetFirstParagraphEffectedByInsert(Document, index);
if (paragraph == null)
Xml.Add(p.Xml);
else
{
XElement[] split = HelperFunctions.SplitParagraph(paragraph, index - paragraph.startIndex);
paragraph.Xml.ReplaceWith
(
split[0],
newXElement,
split[1]
);
}
GetParent(p);
return p;
}
public virtual Paragraph InsertParagraph(Paragraph p)
{
#region Styles
XDocument style_document;
if (p.styles.Count() > 0)
{
Uri style_package_uri = new Uri("/word/styles.xml", UriKind.Relative);
if (!Document.package.PartExists(style_package_uri))
{
PackagePart style_package = Document.package.CreatePart(style_package_uri, "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml", CompressionOption.Maximum);
using (TextWriter tw = new StreamWriter(new PackagePartStream(style_package.GetStream())))
{
style_document = new XDocument
(
new XDeclaration("1.0", "UTF-8", "yes"),
new XElement(XName.Get("styles", DocX.w.NamespaceName))
);
style_document.Save(tw);
}
}
PackagePart styles_document = Document.package.GetPart(style_package_uri);
using (TextReader tr = new StreamReader(styles_document.GetStream()))
{
style_document = XDocument.Load(tr);
XElement styles_element = style_document.Element(XName.Get("styles", DocX.w.NamespaceName));
var ids = from d in styles_element.Descendants(XName.Get("style", DocX.w.NamespaceName))
let a = d.Attribute(XName.Get("styleId", DocX.w.NamespaceName))
where a != null
select a.Value;
foreach (XElement style in p.styles)
{
// If styles_element does not contain this element, then add it.
if (!ids.Contains(style.Attribute(XName.Get("styleId", DocX.w.NamespaceName)).Value))
styles_element.Add(style);
}
}
using (TextWriter tw = new StreamWriter(new PackagePartStream(styles_document.GetStream())))
style_document.Save(tw);
}
#endregion
XElement newXElement = new XElement(p.Xml);
Xml.Add(newXElement);
int index = 0;
if (Document.paragraphLookup.Keys.Count() > 0)
{
index = Document.paragraphLookup.Last().Key;
if (Document.paragraphLookup.Last().Value.Text.Length == 0)
index++;
else
index += Document.paragraphLookup.Last().Value.Text.Length;
}
Paragraph newParagraph = new Paragraph(Document, newXElement, index);
Document.paragraphLookup.Add(index, newParagraph);
GetParent(newParagraph);
return newParagraph;
}
public virtual Paragraph InsertParagraph(int index, string text, bool trackChanges, Formatting formatting)
{
Paragraph newParagraph = new Paragraph(Document, new XElement(DocX.w + "p"), index);
newParagraph.InsertText(0, text, trackChanges, formatting);
Paragraph firstPar = HelperFunctions.GetFirstParagraphEffectedByInsert(Document, index);
if (firstPar != null)
{
var splitindex = index - firstPar.startIndex;
if (splitindex <= 0)
{
firstPar.Xml.ReplaceWith(newParagraph.Xml, firstPar.Xml);
}
else
{
XElement[] splitParagraph = HelperFunctions.SplitParagraph(firstPar, splitindex);
firstPar.Xml.ReplaceWith
(
splitParagraph[0],
newParagraph.Xml,
splitParagraph[1]
);
}
}
else
Xml.Add(newParagraph);
GetParent(newParagraph);
return newParagraph;
}
private ContainerType GetParentFromXmlName(string xmlName)
{
ContainerType parent;
switch (xmlName)
{
case "body":
parent = ContainerType.Body;
break;
case "p":
parent = ContainerType.Paragraph;
break;
case "tbl":
parent = ContainerType.Table;
break;
case "sectPr":
parent = ContainerType.Section;
break;
case "tc":
parent = ContainerType.Cell;
break;
default:
parent = ContainerType.None;
break;
}
return parent;
}
private void GetParent(Paragraph newParagraph)
{
var containerType = GetType();
switch (containerType.Name)
{
case "Body":
newParagraph.ParentContainer = ContainerType.Body;
break;
case "Table":
newParagraph.ParentContainer = ContainerType.Table;
break;
case "TOC":
newParagraph.ParentContainer = ContainerType.TOC;
break;
case "Section":
newParagraph.ParentContainer = ContainerType.Section;
break;
case "Cell":
newParagraph.ParentContainer = ContainerType.Cell;
break;
case "Header":
newParagraph.ParentContainer = ContainerType.Header;
break;
case "Footer":
newParagraph.ParentContainer = ContainerType.Footer;
break;
case "Paragraph":
newParagraph.ParentContainer = ContainerType.Paragraph;
break;
}
}
private ListItemType GetListItemType(string styleName)
{
ListItemType listItemType;
switch (styleName)
{
case "bullet":
listItemType = ListItemType.Bulleted;
break;
default:
listItemType = ListItemType.Numbered;
break;
}
return listItemType;
}
public virtual void InsertSection()
{
InsertSection(false);
}
public virtual void InsertSection(bool trackChanges)
{
var newParagraphSection = new XElement
(
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"))))
);
if (trackChanges)
newParagraphSection = HelperFunctions.CreateEdit(EditType.ins, DateTime.Now, newParagraphSection);
Xml.Add(newParagraphSection);
}
public virtual void InsertSectionPageBreak(bool trackChanges = false)
{
var newParagraphSection = new XElement
(
XName.Get("p", DocX.w.NamespaceName), new XElement(XName.Get("pPr", DocX.w.NamespaceName), new XElement(XName.Get("sectPr", DocX.w.NamespaceName)))
);
if (trackChanges)
newParagraphSection = HelperFunctions.CreateEdit(EditType.ins, DateTime.Now, newParagraphSection);
Xml.Add(newParagraphSection);
}
public virtual Paragraph InsertParagraph(string text)
{
return InsertParagraph(text, false, new Formatting());
}
public virtual Paragraph InsertParagraph(string text, bool trackChanges)
{
return InsertParagraph(text, trackChanges, new Formatting());
}
public virtual Paragraph InsertParagraph(string text, bool trackChanges, Formatting formatting)
{
XElement newParagraph = new XElement
(
XName.Get("p", DocX.w.NamespaceName), new XElement(XName.Get("pPr", DocX.w.NamespaceName)), HelperFunctions.FormatInput(text, formatting.Xml)
);
if (trackChanges)
newParagraph = HelperFunctions.CreateEdit(EditType.ins, DateTime.Now, newParagraph);
Xml.Add(newParagraph);
var paragraphAdded = new Paragraph(Document, newParagraph, 0);
if (this is Cell)
{
var cell = this as Cell;
paragraphAdded.PackagePart = cell.mainPart;
}
else if (this is DocX)
{
paragraphAdded.PackagePart = Document.mainPart;
}
else if (this is Footer)
{
var f = this as Footer;
paragraphAdded.mainPart = f.mainPart;
}
else if (this is Header)
{
var h = this as Header;
paragraphAdded.mainPart = h.mainPart;
}
else
{
Console.WriteLine("No idea what we are {0}", this);
paragraphAdded.PackagePart = Document.mainPart;
}
GetParent(paragraphAdded);
return paragraphAdded;
}
public virtual Paragraph InsertEquation(string equation)
{
Paragraph p = InsertParagraph();
p.AppendEquation(equation);
return p;
}
public virtual Paragraph InsertBookmark(String bookmarkName)
{
var p = InsertParagraph();
p.AppendBookmark(bookmarkName);
return p;
}
public virtual Table InsertTable(int rowCount, int columnCount) //Dmitchern, changed to virtual, and overrided in Table.Cell
{
XElement newTable = HelperFunctions.CreateTable(rowCount, columnCount);
Xml.Add(newTable);
return new Table(Document, newTable) { mainPart = mainPart };
}
public Table InsertTable(int index, int rowCount, int columnCount)
{
XElement newTable = HelperFunctions.CreateTable(rowCount, columnCount);
Paragraph p = HelperFunctions.GetFirstParagraphEffectedByInsert(Document, index);
if (p == null)
Xml.Elements().First().AddFirst(newTable);
else
{
XElement[] split = HelperFunctions.SplitParagraph(p, index - p.startIndex);
p.Xml.ReplaceWith
(
split[0],
newTable,
split[1]
);
}
return new Table(Document, newTable) { mainPart = mainPart };
}
public Table InsertTable(Table t)
{
XElement newXElement = new XElement(t.Xml);
Xml.Add(newXElement);
Table newTable = new Table(Document, newXElement)
{
mainPart = mainPart,
Design = t.Design
};
return newTable;
}
public Table InsertTable(int index, Table t)
{
Paragraph p = HelperFunctions.GetFirstParagraphEffectedByInsert(Document, index);
XElement[] split = HelperFunctions.SplitParagraph(p, index - p.startIndex);
XElement newXElement = new XElement(t.Xml);
p.Xml.ReplaceWith
(
split[0],
newXElement,
split[1]
);
Table newTable = new Table(Document, newXElement)
{
mainPart = mainPart,
Design = t.Design
};
return newTable;
}
internal Container(DocX document, XElement xml)
: base(document, xml)
{