-
Notifications
You must be signed in to change notification settings - Fork 522
/
Copy pathFormattingAssembler.cs
3510 lines (3238 loc) · 142 KB
/
FormattingAssembler.cs
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
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using DocumentFormat.OpenXml.Packaging;
using System.Drawing;
namespace OpenXmlPowerTools
{
public class FormattingAssemblerSettings
{
public bool RemoveStyleNamesFromParagraphAndRunProperties;
public bool ClearStyles;
public bool OrderElementsPerStandard;
public bool CreateHtmlConverterAnnotationAttributes;
public bool RestrictToSupportedNumberingFormats;
public bool RestrictToSupportedLanguages;
public ListItemRetrieverSettings ListItemRetrieverSettings;
public FormattingAssemblerSettings()
{
RemoveStyleNamesFromParagraphAndRunProperties = true;
ClearStyles = true;
OrderElementsPerStandard = true;
CreateHtmlConverterAnnotationAttributes = true;
RestrictToSupportedNumberingFormats = false;
RestrictToSupportedLanguages = false;
ListItemRetrieverSettings = new ListItemRetrieverSettings();
}
}
public static class FormattingAssembler
{
public static WmlDocument AssembleFormatting(WmlDocument document, FormattingAssemblerSettings settings)
{
using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(document))
{
using (WordprocessingDocument doc = streamDoc.GetWordprocessingDocument())
{
AssembleFormatting(doc, settings);
}
return streamDoc.GetModifiedWmlDocument();
}
}
public static void AssembleFormatting(WordprocessingDocument wDoc, FormattingAssemblerSettings settings)
{
FormattingAssemblerInfo fai = new FormattingAssemblerInfo();
XDocument sXDoc = wDoc.MainDocumentPart.StyleDefinitionsPart.GetXDocument();
XElement defaultParagraphStyle = sXDoc
.Root
.Elements(W.style)
.FirstOrDefault(st => st.Attribute(W._default).ToBoolean() == true &&
(string)st.Attribute(W.type) == "paragraph");
if (defaultParagraphStyle != null)
fai.DefaultParagraphStyleName = (string)defaultParagraphStyle.Attribute(W.styleId);
XElement defaultCharacterStyle = sXDoc
.Root
.Elements(W.style)
.FirstOrDefault(st => st.Attribute(W._default).ToBoolean() == true &&
(string)st.Attribute(W.type) == "character");
if (defaultCharacterStyle != null)
fai.DefaultCharacterStyleName = (string)defaultCharacterStyle.Attribute(W.styleId);
XElement defaultTableStyle = sXDoc
.Root
.Elements(W.style)
.FirstOrDefault(st => st.Attribute(W._default).ToBoolean() == true &&
(string)st.Attribute(W.type) == "table");
if (defaultTableStyle != null)
fai.DefaultTableStyleName = (string)defaultTableStyle.Attribute(W.styleId);
ListItemRetrieverSettings listItemRetrieverSettings = new ListItemRetrieverSettings();
AssembleListItemInformation(wDoc, settings.ListItemRetrieverSettings);
foreach (var part in wDoc.ContentParts())
{
var pxd = part.GetXDocument();
FixNonconformantHexValues(pxd.Root);
AnnotateWithGlobalDefaults(wDoc, pxd.Root, settings);
AnnotateTablesWithTableStyles(wDoc, pxd.Root);
AnnotateParagraphs(fai, wDoc, pxd.Root, settings);
AnnotateRuns(fai, wDoc, pxd.Root, settings);
}
NormalizeListItems(fai, wDoc, settings);
if (settings.ClearStyles)
ClearStyles(wDoc);
foreach (var part in wDoc.ContentParts())
{
var pxd = part.GetXDocument();
pxd.Root.Descendants().Attributes().Where(a => a.IsNamespaceDeclaration).Remove();
FormattingAssembler.NormalizePropsForPart(pxd, settings);
var newRoot = (XElement)CleanupTransform(pxd.Root);
pxd.Root.ReplaceWith(newRoot);
part.PutXDocument();
}
}
private static void FixNonconformantHexValues(XElement root)
{
foreach (var tblLook in root.Descendants(W.tblLook))
{
if (tblLook.Attributes().Any(a => a.Name != W.val))
continue;
if (tblLook.Attribute(W.val) == null)
continue;
string hexValue = tblLook.Attribute(W.val).Value;
int val = int.Parse(hexValue, System.Globalization.NumberStyles.HexNumber);
tblLook.Add(new XAttribute(W.firstRow, (val & 0x0020) != 0 ? "1" : "0"));
tblLook.Add(new XAttribute(W.lastRow, (val & 0x0040) != 0 ? "1" : "0"));
tblLook.Add(new XAttribute(W.firstColumn, (val & 0x0080) != 0 ? "1" : "0"));
tblLook.Add(new XAttribute(W.lastColumn, (val & 0x0100) != 0 ? "1" : "0"));
tblLook.Add(new XAttribute(W.noHBand, (val & 0x0200) != 0 ? "1" : "0"));
tblLook.Add(new XAttribute(W.noVBand, (val & 0x0400) != 0 ? "1" : "0"));
}
foreach (var cnfStyle in root.Descendants(W.cnfStyle))
{
if (cnfStyle.Attributes().Any(a => a.Name != W.val))
continue;
if (cnfStyle.Attribute(W.val) == null)
continue;
var va = cnfStyle.Attribute(W.val).Value.ToArray();
cnfStyle.Add(new XAttribute(W.firstRow, va[0]));
cnfStyle.Add(new XAttribute(W.lastRow, va[1]));
cnfStyle.Add(new XAttribute(W.firstColumn, va[2]));
cnfStyle.Add(new XAttribute(W.lastColumn, va[3]));
cnfStyle.Add(new XAttribute(W.oddVBand, va[4]));
cnfStyle.Add(new XAttribute(W.evenVBand, va[5]));
cnfStyle.Add(new XAttribute(W.oddHBand, va[6]));
cnfStyle.Add(new XAttribute(W.evenHBand, va[7]));
cnfStyle.Add(new XAttribute(W.firstRowLastColumn, va[8]));
cnfStyle.Add(new XAttribute(W.firstRowFirstColumn, va[9]));
cnfStyle.Add(new XAttribute(W.lastRowLastColumn, va[10]));
cnfStyle.Add(new XAttribute(W.lastRowFirstColumn, va[11]));
}
}
private static object CleanupTransform(XNode node)
{
XElement element = node as XElement;
if (element != null)
{
if (element.Name == W.tabs && element.Element(W.tab) == null)
return null;
if (element.Name == W.tblStyleRowBandSize || element.Name == W.tblStyleColBandSize)
return null;
// a cleaner solution would be to not include the w:ins and w:del elements when rolling up the paragraph run properties into
// the run properties.
if ((element.Name == W.ins || element.Name == W.del) && element.Parent.Name == W.rPr)
{
if (element.Parent.Parent.Name == W.r || element.Parent.Parent.Name == W.rPrChange)
return null;
}
return new XElement(element.Name,
element.Attributes(),
element.Nodes().Select(n => CleanupTransform(n)));
}
return node;
}
private static void ClearStyles(WordprocessingDocument wDoc)
{
var stylePart = wDoc.MainDocumentPart.StyleDefinitionsPart;
var sXDoc = stylePart.GetXDocument();
var newRoot = new XElement(sXDoc.Root.Name,
sXDoc.Root.Attributes(),
sXDoc.Root.Elements().Select(e =>
{
if (e.Name != W.style)
return e;
return new XElement(e.Name,
e.Attributes(),
e.Element(W.name),
new XElement(W.pPr),
new XElement(W.rPr));
}));
var globalrPr = newRoot
.Elements(W.docDefaults)
.Elements(W.rPrDefault)
.Elements(W.rPr)
.FirstOrDefault();
if (globalrPr != null)
globalrPr.ReplaceWith(new XElement(W.rPr));
var globalpPr = newRoot
.Elements(W.docDefaults)
.Elements(W.pPrDefault)
.Elements(W.pPr)
.FirstOrDefault();
if (globalpPr != null)
globalpPr.ReplaceWith(new XElement(W.pPr));
sXDoc.Root.ReplaceWith(newRoot);
stylePart.PutXDocument();
}
private static void NormalizeListItems(FormattingAssemblerInfo fai, WordprocessingDocument wDoc, FormattingAssemblerSettings settings)
{
foreach (var part in wDoc.ContentParts())
{
var pxd = part.GetXDocument();
XElement newRoot = (XElement)NormalizeListItemsTransform(fai, wDoc, pxd.Root, settings);
if (newRoot.Attribute(XNamespace.Xmlns + "pt14") == null)
newRoot.Add(new XAttribute(XNamespace.Xmlns + "pt14", PtOpenXml.pt.NamespaceName));
if (newRoot.Attribute(XNamespace.Xmlns + "mc") == null)
newRoot.Add(new XAttribute(XNamespace.Xmlns + "mc", MC.mc.NamespaceName));
pxd.Root.ReplaceWith(newRoot);
}
}
private static object NormalizeListItemsTransform(FormattingAssemblerInfo fai, WordprocessingDocument wDoc, XNode node, FormattingAssemblerSettings settings)
{
var element = node as XElement;
if (element != null)
{
if (element.Name == W.p)
{
var li = ListItemRetriever.RetrieveListItem(wDoc, element, settings.ListItemRetrieverSettings);
if (li != null)
{
ListItemRetriever.ListItemInfo listItemInfo = element.Annotation<ListItemRetriever.ListItemInfo>();
var newParaProps = new XElement(W.pPr,
element.Elements(W.pPr).Elements().Where(e => e.Name != W.numPr)
);
XElement listItemRunProps = null;
int? abstractNumId = null;
if (listItemInfo != null)
{
abstractNumId = listItemInfo.AbstractNumId;
var paraStyleRunProps = CharStyleRollup(fai, wDoc, element);
var paragraphStyleName = (string)element
.Elements(W.pPr)
.Elements(W.pStyle)
.Attributes(W.val)
.FirstOrDefault();
string defaultStyleName = (string)wDoc
.MainDocumentPart
.StyleDefinitionsPart
.GetXDocument()
.Root
.Elements(W.style)
.Where(s => (string)s.Attribute(W.type) == "paragraph" && s.Attribute(W._default).ToBoolean() == true)
.Attributes(W.styleId)
.FirstOrDefault();
if (paragraphStyleName == null)
paragraphStyleName = defaultStyleName;
XDocument stylesXDoc = wDoc
.MainDocumentPart
.StyleDefinitionsPart
.GetXDocument();
// put together run props for list item.
XElement lvlStyleRpr = ParaStyleRunPropsStack(wDoc, paragraphStyleName)
.Aggregate(new XElement(W.rPr),
(r, s) =>
{
var newCharStyleRunProps = MergeStyleElement(s, r);
return newCharStyleRunProps;
});
var mergedRunProps = MergeStyleElement(lvlStyleRpr, paraStyleRunProps);
var accumulatedRunProps = element.Elements(PtOpenXml.pPr).Elements(W.rPr).FirstOrDefault();
if (accumulatedRunProps != null)
mergedRunProps = MergeStyleElement(accumulatedRunProps, mergedRunProps);
var listItemLvl = listItemInfo.Lvl(ListItemRetriever.GetParagraphLevel(element));
var listItemLvlRunProps = listItemLvl.Elements(W.rPr).FirstOrDefault();
listItemRunProps = MergeStyleElement(listItemLvlRunProps, mergedRunProps);
if ((string)listItemLvl.Elements(W.numFmt).Attributes(W.val).FirstOrDefault() == "bullet")
{
listItemRunProps.Elements(W.rtl).Remove();
}
else
{
var pPr = element.Element(PtOpenXml.pPr);
if (pPr != null)
{
XElement bidiel = pPr.Element(W.bidi);
bool bidi = bidiel != null && (bidiel.Attribute(W.val) == null || bidiel.Attribute(W.val).ToBoolean() == true);
if (bidi)
{
listItemRunProps = MergeStyleElement(new XElement(W.rPr,
new XElement(W.rtl)), listItemRunProps);
}
}
}
}
var paragraphLevel = ListItemRetriever.GetParagraphLevel(element);
ListItemRetriever.LevelNumbers levelNums = element.Annotation<ListItemRetriever.LevelNumbers>();
string levelNumsString = levelNums
.LevelNumbersArray
.Take(paragraphLevel + 1)
.Select(i => i.ToString() + ".")
.StringConcatenate()
.TrimEnd('.');
var listItemRun = new XElement(W.r,
new XAttribute(PtOpenXml.ListItemRun, levelNumsString),
element.Attribute(PtOpenXml.FontName),
element.Attribute(PtOpenXml.LanguageType),
listItemRunProps,
new XElement(W.t,
new XAttribute(XNamespace.Xml + "space", "preserve"),
li));
AdjustFontAttributes(wDoc, listItemRun, null, listItemRunProps, settings);
var lvl = listItemInfo.Lvl(ListItemRetriever.GetParagraphLevel(element));
XElement suffix = new XElement(W.tab);
var su = (string)lvl.Elements(W.suff).Attributes(W.val).FirstOrDefault();
if (su == "space")
suffix = new XElement(W.t,
new XAttribute(XNamespace.Xml + "space", "preserve"),
" ");
else if (su == "nothing")
suffix = null;
var jc = (string)lvl.Elements(W.lvlJc).Attributes(W.val).FirstOrDefault();
if (jc == "right")
{
var accumulatedParaProps = element.Element(PtOpenXml.pPr);
var hangingAtt = accumulatedParaProps.Elements(W.ind).Attributes(W.hanging).FirstOrDefault();
if (hangingAtt == null)
{
var listItemRunLength = WordprocessingMLUtil.CalcWidthOfRunInTwips(listItemRun);
var ind = accumulatedParaProps.Element(W.ind);
if (ind == null)
{
ind = new XElement(W.ind);
accumulatedParaProps.Add(ind);
}
ind.Add(new XAttribute(W.hanging, listItemRunLength.ToString()));
}
else
{
var hanging = (int)hangingAtt;
var listItemRunLength = WordprocessingMLUtil.CalcWidthOfRunInTwips(listItemRun);
hanging += listItemRunLength; // should be width of list item, in twips
hangingAtt.Value = hanging.ToString();
}
}
else if (jc == "center")
{
var accumulatedParaProps = element.Element(PtOpenXml.pPr);
var hangingAtt = accumulatedParaProps.Elements(W.ind).Attributes(W.hanging).FirstOrDefault();
if (hangingAtt == null)
{
var listItemRunLength = WordprocessingMLUtil.CalcWidthOfRunInTwips(listItemRun);
var ind = accumulatedParaProps.Element(W.ind);
if (ind == null)
{
ind = new XElement(W.ind);
accumulatedParaProps.Add(ind);
}
ind.Add(new XAttribute(W.hanging, (listItemRunLength / 2).ToString()));
}
else
{
var hanging = (int)hangingAtt;
var listItemRunLength = WordprocessingMLUtil.CalcWidthOfRunInTwips(listItemRun);
hanging += (listItemRunLength / 2); // should be half of width of list item, in twips
hangingAtt.Value = hanging.ToString();
}
}
AddTabAtLeftIndent(element.Element(PtOpenXml.pPr));
XElement newPara = new XElement(W.p,
element.Attribute(PtOpenXml.FontName),
element.Attribute(PtOpenXml.LanguageType),
element.Attribute(PtOpenXml.Unid),
new XAttribute(PtOpenXml.AbstractNumId, abstractNumId),
newParaProps,
listItemRun,
suffix != null ?
new XElement(W.r,
new XAttribute(PtOpenXml.ListItemRun, levelNumsString),
listItemRunProps,
suffix) : null,
element.Elements().Where(e => e.Name != W.pPr).Select(n => NormalizeListItemsTransform(fai, wDoc, n, settings)));
return newPara;
}
}
return new XElement(element.Name,
element.Attributes(),
element.Nodes().Select(n => NormalizeListItemsTransform(fai, wDoc, n, settings)));
}
return node;
}
private static void AddTabAtLeftIndent(XElement pPr)
{
int left = 0;
var ind = pPr.Element(W.ind);
// todo need to handle W.start
if (pPr.Attribute(W.left) != null)
left = (int)pPr.Attribute(W.left);
var tabs = pPr.Element(W.tabs);
if (tabs == null)
{
tabs = new XElement(W.tabs);
pPr.Add(tabs);
}
var tabAtLeft = tabs.Elements(W.tab).FirstOrDefault(t => (int)t.Attribute(W.pos) == left);
if (tabAtLeft == null)
{
tabs.Add(
new XElement(W.tab,
new XAttribute(W.val, "left"),
new XAttribute(W.pos, left)));
}
}
public static XName[] PtNamesToKeep = new[] {
PtOpenXml.FontName,
PtOpenXml.AbstractNumId,
PtOpenXml.StyleName,
PtOpenXml.LanguageType,
PtOpenXml.ListItemRun,
PtOpenXml.Unid,
};
public static void NormalizePropsForPart(XDocument pxd, FormattingAssemblerSettings settings)
{
if (settings.CreateHtmlConverterAnnotationAttributes)
{
pxd.Root.Descendants().Attributes().Where(d => d.Name.Namespace == PtOpenXml.pt &&
!PtNamesToKeep.Contains(d.Name)).Remove();
if (pxd.Root.Attribute(XNamespace.Xmlns + "pt14") == null)
pxd.Root.Add(new XAttribute(XNamespace.Xmlns + "pt14", PtOpenXml.pt.NamespaceName));
if (pxd.Root.Attribute(XNamespace.Xmlns + "mc") == null)
pxd.Root.Add(new XAttribute(XNamespace.Xmlns + "mc", MC.mc.NamespaceName));
XAttribute mci = pxd.Root.Attribute(MC.Ignorable);
if (mci != null)
{
if (!pxd.Root.Attribute(MC.Ignorable).Value.Contains("pt14"))
{
var ig = pxd.Root.Attribute(MC.Ignorable).Value + " pt14";
mci.Value = ig;
}
}
else
{
pxd.Root.Add(new XAttribute(MC.Ignorable, "pt14"));
}
}
else
{
pxd.Root.Descendants().Attributes().Where(d => d.Name.Namespace == PtOpenXml.pt).Remove();
}
var runProps = pxd.Root.Descendants(PtOpenXml.rPr).ToList();
foreach (var item in runProps)
{
XElement newRunProps = new XElement(W.rPr,
item.Attributes(),
item.Elements());
XElement parent = item.Parent;
if (parent.Name == W.p)
{
XElement existingParaProps = parent.Element(W.pPr);
if (existingParaProps == null)
{
existingParaProps = new XElement(W.pPr);
parent.Add(existingParaProps);
}
XElement existingRunProps = existingParaProps.Element(W.rPr);
if (existingRunProps != null)
{
if (!settings.RemoveStyleNamesFromParagraphAndRunProperties)
{
if (newRunProps.Element(W.rStyle) == null)
newRunProps.Add(existingRunProps.Element(W.rStyle));
}
existingRunProps.ReplaceWith(newRunProps);
}
else
existingParaProps.Add(newRunProps);
}
else
{
XElement existingRunProps = parent.Element(W.rPr);
if (existingRunProps != null)
{
if (!settings.RemoveStyleNamesFromParagraphAndRunProperties)
{
if (newRunProps.Element(W.rStyle) == null)
newRunProps.Add(existingRunProps.Element(W.rStyle));
}
existingRunProps.ReplaceWith(newRunProps);
}
else
parent.Add(newRunProps);
}
}
var paraProps = pxd.Root.Descendants(PtOpenXml.pPr).ToList();
foreach (var item in paraProps)
{
var paraRunProps = item.Parent.Elements(W.pPr).Elements(W.rPr).FirstOrDefault();
var merged = MergeStyleElement(item.Element(W.rPr), paraRunProps);
if (!settings.RemoveStyleNamesFromParagraphAndRunProperties)
{
if (merged.Element(W.rStyle) == null)
{
merged.Add(paraRunProps.Element(W.rStyle));
}
}
XElement newParaProps = new XElement(W.pPr,
item.Attributes(),
item.Elements().Where(e => e.Name != W.rPr),
merged);
XElement para = item.Parent;
XElement existingParaProps = para.Element(W.pPr);
if (existingParaProps != null)
{
if (!settings.RemoveStyleNamesFromParagraphAndRunProperties)
{
if (newParaProps.Element(W.pStyle) == null)
newParaProps.Add(existingParaProps.Element(W.pStyle));
}
existingParaProps.ReplaceWith(newParaProps);
}
else
para.Add(newParaProps);
}
var tblProps = pxd.Root.Descendants(PtOpenXml.tblPr).ToList();
foreach (var item in tblProps)
{
XElement newTblProps = new XElement(item);
newTblProps.Name = W.tblPr;
XElement table = item.Parent;
XElement existingTableProps = table.Element(W.tblPr);
if (existingTableProps != null)
existingTableProps.ReplaceWith(newTblProps);
else
table.AddFirst(newTblProps);
}
var trProps = pxd.Root.Descendants(PtOpenXml.trPr).ToList();
foreach (var item in trProps)
{
XElement newTrProps = new XElement(item);
newTrProps.Name = W.trPr;
XElement row = item.Parent;
XElement existingRowProps = row.Element(W.trPr);
if (existingRowProps != null)
existingRowProps.ReplaceWith(newTrProps);
else
row.AddFirst(newTrProps);
}
var tcProps = pxd.Root.Descendants(PtOpenXml.tcPr).ToList();
foreach (var item in tcProps)
{
XElement newTcProps = new XElement(item);
newTcProps.Name = W.tcPr;
XElement row = item.Parent;
XElement existingRowProps = row.Element(W.tcPr);
if (existingRowProps != null)
existingRowProps.ReplaceWith(newTcProps);
else
row.AddFirst(newTcProps);
}
pxd.Root.Descendants(W.numPr).Remove();
if (settings.RemoveStyleNamesFromParagraphAndRunProperties)
{
pxd.Root.Descendants(W.pStyle).Where(ps => ps.Parent.Name == W.pPr).Remove();
pxd.Root.Descendants(W.rStyle).Where(ps => ps.Parent.Name == W.rPr).Remove();
}
pxd.Root.Descendants(W.tblStyle).Where(ps => ps.Parent.Name == W.tblPr).Remove();
pxd.Root.Descendants().Where(d => d.Name.Namespace == PtOpenXml.pt).Remove();
if (settings.OrderElementsPerStandard)
{
XElement newRoot = (XElement)WordprocessingMLUtil.WmlOrderElementsPerStandard(pxd.Root);
pxd.Root.ReplaceWith(newRoot);
}
}
private static void AssembleListItemInformation(WordprocessingDocument wordDoc, ListItemRetrieverSettings settings)
{
foreach (var part in wordDoc.ContentParts())
{
XDocument xDoc = part.GetXDocument();
foreach (var para in xDoc.Descendants(W.p))
{
ListItemRetriever.RetrieveListItem(wordDoc, para, settings);
}
}
}
private static void AnnotateWithGlobalDefaults(WordprocessingDocument wDoc, XElement rootElement, FormattingAssemblerSettings settings)
{
XElement globalDefaultParaProps = null;
XElement globalDefaultParaPropsAsDefined = null;
XElement globalDefaultRunProps = null;
XElement globalDefaultRunPropsAsDefined = null;
XDocument sXDoc = wDoc.MainDocumentPart.StyleDefinitionsPart.GetXDocument();
var defaultParaStyleName = (string)sXDoc
.Root
.Elements(W.style)
.Where(st => (string)st.Attribute(W.type) == "paragraph" && st.Attribute(W._default).ToBoolean() == true)
.Attributes(W.styleId)
.FirstOrDefault();
var defaultCharStyleName = (string)sXDoc
.Root
.Elements(W.style)
.Where(st => (string)st.Attribute(W.type) == "character" && st.Attribute(W._default).ToBoolean() == true)
.Attributes(W.styleId)
.FirstOrDefault();
XElement docDefaults = sXDoc.Root.Element(W.docDefaults);
if (docDefaults != null)
{
globalDefaultParaPropsAsDefined = docDefaults.Elements(W.pPrDefault).Elements(W.pPr)
.FirstOrDefault();
if (globalDefaultParaPropsAsDefined == null)
globalDefaultParaPropsAsDefined = new XElement(W.pPr,
new XElement(W.rPr));
globalDefaultRunPropsAsDefined = docDefaults.Elements(W.rPrDefault).Elements(W.rPr)
.FirstOrDefault();
if (globalDefaultRunPropsAsDefined == null)
globalDefaultRunPropsAsDefined = new XElement(W.rPr);
if (globalDefaultRunPropsAsDefined.Element(W.rFonts) == null)
globalDefaultRunPropsAsDefined.Add(
new XElement(W.rFonts,
new XAttribute(W.ascii, "Times New Roman"),
new XAttribute(W.hAnsi, "Times New Roman"),
new XAttribute(W.cs, "Times New Roman")));
if (globalDefaultRunPropsAsDefined.Element(W.sz) == null)
globalDefaultRunPropsAsDefined.Add(
new XElement(W.sz,
new XAttribute(W.val, "20")));
if (globalDefaultRunPropsAsDefined.Element(W.szCs) == null)
globalDefaultRunPropsAsDefined.Add(
new XElement(W.szCs,
new XAttribute(W.val, "20")));
var runPropsForGlobalDefaultParaProps = MergeStyleElement(globalDefaultRunPropsAsDefined, globalDefaultParaPropsAsDefined.Element(W.rPr));
globalDefaultParaProps = new XElement(globalDefaultParaPropsAsDefined.Name,
globalDefaultParaPropsAsDefined.Attributes(),
globalDefaultParaPropsAsDefined.Elements().Where(e => e.Name != W.rPr),
runPropsForGlobalDefaultParaProps);
globalDefaultRunProps = MergeStyleElement(globalDefaultParaPropsAsDefined.Element(W.rPr), globalDefaultRunPropsAsDefined);
}
var rPr = new XElement(W.rPr,
new XElement(W.rFonts,
new XAttribute(W.ascii, "Times New Roman"),
new XAttribute(W.hAnsi, "Times New Roman"),
new XAttribute(W.cs, "Times New Roman")),
new XElement(W.sz,
new XAttribute(W.val, "20")),
new XElement(W.szCs,
new XAttribute(W.val, "20")));
if (globalDefaultParaProps == null)
globalDefaultParaProps = new XElement(W.pPr, rPr);
if (globalDefaultRunProps == null)
globalDefaultRunProps = rPr;
XElement ptGlobalDefaultParaProps = new XElement(globalDefaultParaProps);
XElement ptGlobalDefaultRunProps = new XElement(globalDefaultRunProps);
ptGlobalDefaultParaProps.Name = PtOpenXml.pPr;
ptGlobalDefaultRunProps.Name = PtOpenXml.rPr;
var parasAndRuns = rootElement.Descendants().Where(d =>
{
return d.Name == W.p || d.Name == W.r;
});
if (settings.CreateHtmlConverterAnnotationAttributes)
{
foreach (var d in parasAndRuns)
{
if (d.Name == W.p)
{
var pStyle = (string)d.Elements(W.pPr).Elements(W.pStyle).Attributes(W.val).FirstOrDefault();
if (pStyle == null)
pStyle = defaultParaStyleName;
if (pStyle != null)
{
if (d.Attribute(PtOpenXml.StyleName) != null)
d.Attribute(PtOpenXml.StyleName).Value = pStyle;
else
d.Add(new XAttribute(PtOpenXml.StyleName, pStyle));
}
d.Add(ptGlobalDefaultParaProps);
}
else
{
var rStyle = (string)d.Elements(W.rPr).Elements(W.rStyle).Attributes(W.val).FirstOrDefault();
if (rStyle == null)
rStyle = defaultCharStyleName;
if (rStyle != null)
{
if (d.Attribute(PtOpenXml.StyleName) != null)
d.Attribute(PtOpenXml.StyleName).Value = rStyle;
else
d.Add(new XAttribute(PtOpenXml.StyleName, rStyle));
}
d.Add(ptGlobalDefaultRunProps);
}
}
}
else
{
foreach (var d in parasAndRuns)
{
if (d.Name == W.p)
{
d.Add(ptGlobalDefaultParaProps);
}
else
{
d.Add(ptGlobalDefaultRunProps);
}
}
}
}
private static XElement BlankTcBorders = new XElement(W.tcBorders,
new XElement(W.top, new XAttribute(W.val, "nil")),
new XElement(W.left, new XAttribute(W.val, "nil")),
new XElement(W.bottom, new XAttribute(W.val, "nil")),
new XElement(W.right, new XAttribute(W.val, "nil")));
private static void AnnotateTablesWithTableStyles(WordprocessingDocument wDoc, XElement rootElement)
{
XDocument sXDoc = wDoc.MainDocumentPart.StyleDefinitionsPart.GetXDocument();
foreach (var tbl in rootElement.Descendants(W.tbl))
{
string tblStyleName = (string)tbl.Elements(W.tblPr).Elements(W.tblStyle).Attributes(W.val).FirstOrDefault();
if (tblStyleName != null)
{
XElement style = TableStyleRollup(wDoc, tblStyleName);
// annotate table with table style, in PowerTools namespace
style.Name = PtOpenXml.style;
tbl.Add(style);
// merge tblPr in table style with tblPr of the table
// annnotate in PowerTools namespace
XElement tblPr2 = style.Element(W.tblPr);
XElement tblPr3 = MergeStyleElement(tbl.Element(W.tblPr), tblPr2, true);
if (tblPr3 != null)
{
XElement newTblPr = new XElement(tblPr3);
newTblPr.Name = PtOpenXml.pt + "tblPr";
tbl.Add(newTblPr);
}
AddTcPrPtToEveryCell(tbl);
AddOuterBorders(tbl, style);
var tableTcPr = style.Element(W.tcPr);
if (tableTcPr != null)
{
foreach (var row in tbl.Elements(W.tr))
{
foreach (var cell in row.Elements(W.tc))
{
bool tcPrPtExists = false;
var tcPrPt = cell.Element(PtOpenXml.pt + "tcPr");
if (tcPrPt != null)
tcPrPtExists = true;
else
tcPrPt = new XElement(W.tcPr);
tcPrPt = MergeStyleElement(tableTcPr, tcPrPt);
var newTcPrPt = new XElement(tcPrPt);
newTcPrPt.Name = PtOpenXml.tcPr;
if (tcPrPtExists)
cell.Element(PtOpenXml.tcPr).ReplaceWith(newTcPrPt);
else
cell.Add(newTcPrPt);
}
}
}
// Iterate through every row and cell in the table, rolling up row properties and cell properties
// as appropriate per the cnfStyle element, then replacing the row and cell properties
foreach (var row in tbl.Elements(W.tr))
{
XElement trPr2 = null;
trPr2 = style.Element(W.trPr);
if (trPr2 == null)
trPr2 = new XElement(W.trPr);
XElement rowCnf = row.Elements(W.trPr).Elements(W.cnfStyle).FirstOrDefault();
if (rowCnf != null)
{
foreach (var ot in TableStyleOverrideTypes)
{
XName attName = TableStyleOverrideXNameMap[ot];
if (rowCnf != null && rowCnf.Attribute(attName).ToBoolean() == true)
{
XElement o = style
.Elements(W.tblStylePr)
.Where(tsp => (string)tsp.Attribute(W.type) == ot)
.FirstOrDefault();
if (o != null)
{
XElement ottrPr = o.Element(W.trPr);
trPr2 = MergeStyleElement(ottrPr, trPr2);
}
}
}
}
trPr2 = MergeStyleElement(row.Element(W.trPr), trPr2);
if (trPr2.HasElements)
{
trPr2.Name = PtOpenXml.pt + "trPr";
row.Add(trPr2);
}
}
foreach (var ot in TableStyleOverrideTypes)
{
XName attName = TableStyleOverrideXNameMap[ot];
if (attName == W.oddHBand ||
attName == W.evenHBand ||
attName == W.firstRow ||
attName == W.lastRow)
{
foreach (var row in tbl.Elements(W.tr))
{
XElement rowCnf = row.Elements(W.trPr).Elements(W.cnfStyle).FirstOrDefault();
if (rowCnf != null && rowCnf.Attribute(attName).ToBoolean() == true)
{
XElement o = style
.Elements(W.tblStylePr)
.Where(tsp => (string)tsp.Attribute(W.type) == ot)
.FirstOrDefault();
if (o != null)
{
foreach (var cell in row.Elements(W.tc))
{
bool tcPrPtExists = false;
var tcPrPt = cell.Element(PtOpenXml.pt + "tcPr");
if (tcPrPt != null)
tcPrPtExists = true;
else
tcPrPt = new XElement(W.tcPr);
tcPrPt = MergeStyleElement(o.Element(W.tcPr), tcPrPt);
var newTcPrPt = new XElement(tcPrPt);
newTcPrPt.Name = PtOpenXml.pt + "tcPr";
if (tcPrPtExists)
cell.Element(PtOpenXml.pt + "tcPr").ReplaceWith(newTcPrPt);
else
cell.Add(newTcPrPt);
}
}
}
}
}
else if (attName == W.firstColumn ||
attName == W.lastColumn ||
attName == W.oddVBand ||
attName == W.evenVBand)
{
foreach (var row in tbl.Elements(W.tr))
{
foreach (var cell in row.Elements(W.tc))
{
ApplyCndFmtToCell(style, ot, attName, cell);
}
}
}
else if (attName == W.firstRowLastColumn)
{
var row = tbl.Elements(W.tr).FirstOrDefault();
if (row != null)
{
var cell = row.Elements(W.tc).LastOrDefault();
if (cell != null)
ApplyCndFmtToCell(style, ot, attName, cell);
}
}
else if (attName == W.firstRowFirstColumn)
{
var row = tbl.Elements(W.tr).FirstOrDefault();
if (row != null)
{
var cell = row.Elements(W.tc).FirstOrDefault();
if (cell != null)
ApplyCndFmtToCell(style, ot, attName, cell);
}
}
else if (attName == W.lastRowLastColumn)
{
var row = tbl.Elements(W.tr).LastOrDefault();
if (row != null)
{
var cell = row.Elements(W.tc).LastOrDefault();
if (cell != null)
ApplyCndFmtToCell(style, ot, attName, cell);
}
}
else if (attName == W.lastRowFirstColumn)
{
var row = tbl.Elements(W.tr).LastOrDefault();
if (row != null)
{
var cell = row.Elements(W.tc).FirstOrDefault();
if (cell != null)
ApplyCndFmtToCell(style, ot, attName, cell);
}
}
}
ProcessInnerBorders(tbl, style);
}
else
{
var tblPr = new XElement(W.tblPr);
XElement tblPr3 = MergeStyleElement(tbl.Element(W.tblPr), tblPr, true);
if (tblPr3 != null)
{
XElement newTblPr = new XElement(tblPr3);
newTblPr.Name = PtOpenXml.pt + "tblPr";
tbl.Add(newTblPr);
}
AddTcPrPtToEveryCell(tbl);
}
RollInDirectFormatting(tbl); // it is important that this is last. This merges in direct formatting.
}
}
private static void AddTcPrPtToEveryCell(XElement tbl)
{
foreach (var row in tbl.Elements(W.tr))
{
foreach (var cell in row.Elements(W.tc))
{
var tcPrPt = cell.Element(PtOpenXml.pt + "tcPr");
if (tcPrPt != null)
continue;
tcPrPt = new XElement(PtOpenXml.pt + "tcPr",
new XElement(W.tcBorders));
cell.Add(tcPrPt);
}
}
}
private static void ApplyCndFmtToCell(XElement style, string ot, XName attName, XElement cell)
{
XElement cellCnf = cell.Elements(W.tcPr).Elements(W.cnfStyle).FirstOrDefault();
if (cellCnf != null && cellCnf.Attribute(attName).ToBoolean() == true)
{
XElement o = style
.Elements(W.tblStylePr)
.Where(tsp => (string)tsp.Attribute(W.type) == ot)
.FirstOrDefault();
if (o != null)
{
bool tcPrPtExists = false;
var tcPrPt = cell.Element(PtOpenXml.pt + "tcPr");
if (tcPrPt != null)
tcPrPtExists = true;
else
tcPrPt = new XElement(W.tcPr);
tcPrPt = MergeStyleElement(o.Element(W.tcPr), tcPrPt);
var newTcPrPt = new XElement(tcPrPt);
newTcPrPt.Name = PtOpenXml.pt + "tcPr";
if (tcPrPtExists)
cell.Element(PtOpenXml.pt + "tcPr").ReplaceWith(newTcPrPt);
else
cell.Add(newTcPrPt);
}
}
}
private static void RollInDirectFormatting(XElement tbl)
{
foreach (var row in tbl.Elements(W.tr))
{
foreach (var cell in row.Elements(W.tc))
{
var ptTcPr = cell.Element(PtOpenXml.pt + "tcPr");
var tcPr = cell.Element(W.tcPr);
var mTcPr = MergeStyleElement(tcPr, ptTcPr);
if (mTcPr == null)
{
mTcPr = new XElement(PtOpenXml.pt + "tcPr");
cell.Add(tcPr);