-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathDocumentAssembler.cs
1516 lines (1395 loc) · 70 KB
/
DocumentAssembler.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.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.Linq;
using System.Xml.XPath;
using System.Xml.Schema;
using DocumentFormat.OpenXml.Office.CustomUI;
using DocumentFormat.OpenXml.Packaging;
using Clippit;
using System.Collections;
using DocumentFormat.OpenXml.Drawing.Wordprocessing;
using Path = System.IO.Path;
namespace Clippit.Word
{
public static class DocumentAssembler
{
public static WmlDocument AssembleDocument(WmlDocument templateDoc, XmlDocument data, out bool templateError)
{
var xDoc = data.GetXDocument();
return AssembleDocument(templateDoc, xDoc.Root, out templateError);
}
public static WmlDocument AssembleDocument(WmlDocument templateDoc, XElement data, out bool templateError)
{
var byteArray = templateDoc.DocumentByteArray;
using var mem = new MemoryStream();
mem.Write(byteArray, 0, (int)byteArray.Length);
using (var wordDoc = WordprocessingDocument.Open(mem, true))
{
if (RevisionAccepter.HasTrackedRevisions(wordDoc))
throw new OpenXmlPowerToolsException("Invalid DocumentAssembler template - contains tracked revisions");
// calculate and store the max docPr id for later use when adding image objects
var macDocPrId = GetMaxDocPrId(wordDoc);
var te = new TemplateError();
foreach (var part in wordDoc.ContentParts())
{
ProcessTemplatePart(data, te, part);
}
templateError = te.HasError;
// update image docPr ids for the whole document
FixUpDocPrIds(wordDoc, macDocPrId);
}
var assembledDocument = new WmlDocument("TempFileName.docx", mem.ToArray());
return assembledDocument;
}
private static void ProcessTemplatePart(XElement data, TemplateError te, OpenXmlPart part)
{
var xDoc = part.GetXDocument();
var xDocRoot = RemoveGoBackBookmarks(xDoc.Root);
// process diagrams part
// TODO: consider splitting this method into two for clarity, so, for example, there will be
// TODO: pipeline-like processing: first the diagram, then the document part, or vice versa
var diagramPart = part.GetPartsOfType<DiagramDataPart>().FirstOrDefault();
if (diagramPart != null)
{
var diagramDoc = diagramPart.GetXDocument();
if (diagramDoc != null)
{
var dataPartRoot = diagramDoc.Root;
if (dataPartRoot != null)
{
dataPartRoot = (XElement)TransformToMetadata(dataPartRoot, data, te);
// do the actual content replacement
dataPartRoot = (XElement)ContentReplacementTransform(dataPartRoot, data, te, part);
diagramDoc.Elements().First().ReplaceWith(dataPartRoot);
diagramPart.PutXDocument();
}
}
}
// content controls in cells can surround the W.tc element, so transform so that such content controls are within the cell content
xDocRoot = (XElement)NormalizeContentControlsInCells(xDocRoot);
xDocRoot = (XElement)TransformToMetadata(xDocRoot, data, te);
// Table might have been placed at run-level, when it should be at block-level, so fix this.
// Repeat, EndRepeat, Conditional, EndConditional are allowed at run level, but only if there is a matching pair
// if there is only one Repeat, EndRepeat, Conditional, EndConditional, then move to block level.
// if there is a matching pair, then is OK.
xDocRoot = (XElement)ForceBlockLevelAsAppropriate(xDocRoot, te);
NormalizeTablesRepeatAndConditional(xDocRoot, te);
// any EndRepeat, EndConditional that remain are orphans, so replace with an error
ProcessOrphanEndRepeatEndConditional(xDocRoot, te);
// do the actual content replacement
xDocRoot = (XElement)ContentReplacementTransform(xDocRoot, data, te, part);
xDoc.Elements().First().ReplaceWith(xDocRoot);
part.PutXDocument();
return;
}
private static XName[] s_MetaToForceToBlock = new XName[] {
PA.Conditional,
PA.EndConditional,
PA.Repeat,
PA.EndRepeat,
PA.Table,
PA.Image
};
private static object ForceBlockLevelAsAppropriate(XNode node, TemplateError te)
{
if (node is XElement element)
{
if (element.Name == W.p)
{
var childMeta = element.Elements().Where(n => s_MetaToForceToBlock.Contains(n.Name)).ToList();
if (childMeta.Count() == 1)
{
var child = childMeta.First();
var otherTextInParagraph = element.Elements(W.r).Elements(W.t).Select(t => (string)t).StringConcatenate().Trim();
if (otherTextInParagraph != "")
{
var newPara = new XElement(element);
var newMeta = newPara.Elements().First(n => s_MetaToForceToBlock.Contains(n.Name));
newMeta.ReplaceWith(CreateRunErrorMessage("Error: Unmatched metadata can't be in paragraph with other text", te));
return newPara;
}
var meta = new XElement(child.Name,
child.Attributes(),
new XElement(W.p,
element.Attributes(),
element.Elements(W.pPr),
child.Elements()));
return meta;
}
var count = childMeta.Count();
if (count % 2 == 0)
{
if (childMeta.Count(c => c.Name == PA.Repeat) != childMeta.Count(c => c.Name == PA.EndRepeat))
return CreateContextErrorMessage(element, "Error: Mismatch Repeat / EndRepeat at run level", te);
if (childMeta.Count(c => c.Name == PA.Conditional) != childMeta.Count(c => c.Name == PA.EndConditional))
return CreateContextErrorMessage(element, "Error: Mismatch Conditional / EndConditional at run level", te);
return new XElement(element.Name,
element.Attributes(),
element.Nodes().Select(n => ForceBlockLevelAsAppropriate(n, te)));
}
else
{
return CreateContextErrorMessage(element, "Error: Invalid metadata at run level", te);
}
}
return new XElement(element.Name,
element.Attributes(),
element.Nodes().Select(n => ForceBlockLevelAsAppropriate(n, te)));
}
return node;
}
private static void ProcessOrphanEndRepeatEndConditional(XElement xDocRoot, TemplateError te)
{
foreach (var element in xDocRoot.Descendants(PA.EndRepeat).ToList())
{
var error = CreateContextErrorMessage(element, "Error: EndRepeat without matching Repeat", te);
element.ReplaceWith(error);
}
foreach (var element in xDocRoot.Descendants(PA.EndConditional).ToList())
{
var error = CreateContextErrorMessage(element, "Error: EndConditional without matching Conditional", te);
element.ReplaceWith(error);
}
}
private static XElement RemoveGoBackBookmarks(XElement xElement)
{
var cloneXDoc = new XElement(xElement);
while (true)
{
var bm = cloneXDoc.DescendantsAndSelf(W.bookmarkStart).FirstOrDefault(b => (string)b.Attribute(W.name) == "_GoBack");
if (bm is null)
break;
var id = (string)bm.Attribute(W.id);
var endBm = cloneXDoc.DescendantsAndSelf(W.bookmarkEnd).FirstOrDefault(b => (string)b.Attribute(W.id) == id);
bm.Remove();
endBm.Remove();
}
return cloneXDoc;
}
// this transform inverts content controls that surround W.tc elements. After transforming, the W.tc will contain
// the content control, which contains the paragraph content of the cell.
private static object NormalizeContentControlsInCells(XNode node)
{
if (node is XElement element)
{
if (element.Name == W.sdt && element.Parent.Name == W.tr)
{
var newCell = new XElement(W.tc,
element.Elements(W.tc).Elements(W.tcPr),
new XElement(W.sdt,
element.Elements(W.sdtPr),
element.Elements(W.sdtEndPr),
new XElement(W.sdtContent,
element.Elements(W.sdtContent).Elements(W.tc).Elements().Where(e => e.Name != W.tcPr))));
return newCell;
}
return new XElement(element.Name,
element.Attributes(),
element.Nodes().Select(NormalizeContentControlsInCells));
}
return node;
}
// The following method is written using tree modification, not RPFT, because it is easier to write in this fashion.
// These types of operations are not as easy to write using RPFT.
// Unless you are completely clear on the semantics of LINQ to XML DML, do not make modifications to this method.
private static void NormalizeTablesRepeatAndConditional(XElement xDoc, TemplateError te)
{
var tables = xDoc.Descendants(PA.Table).ToList();
foreach (var table in tables)
{
var followingElement = table.ElementsAfterSelf().FirstOrDefault(e => e.Name == W.tbl || e.Name == W.p);
if (followingElement == null || followingElement.Name != W.tbl)
{
table.ReplaceWith(CreateParaErrorMessage("Table metadata is not immediately followed by a table", te));
continue;
}
// remove superflous paragraph from Table metadata
table.RemoveNodes();
// detach w:tbl from parent, and add to Table metadata
followingElement.Remove();
table.Add(followingElement);
}
var images = xDoc.Descendants(PA.Image).ToList();
foreach (var image in images)
{
var followingElement = image.ElementsAfterSelf().FirstOrDefault(e => e.Name == W.sdt || e.Name == W.p);
if (followingElement == null)
{
image.ReplaceWith(CreateParaErrorMessage("Image metadata is not immediately followed by an image", te));
continue;
}
// get sdt element (can also be within a paragraph) and check it's contents
var sdt = followingElement.Name == W.p ? followingElement.Elements().FirstOrDefault(e => e.Name == W.sdt) : followingElement;
if (sdt != null && sdt.Name == W.sdt)
{
// get sdt properties
var sdtPr = sdt.Elements().FirstOrDefault(e => e.Name == W.sdtPr);
if (sdtPr != null)
{
// check for properties if contain picture
var picture = sdtPr.Elements().FirstOrDefault(e => e.Name == W.picture);
if (picture == null)
{
image.ReplaceWith(
CreateParaErrorMessage("Image metadata does not contain picture element", te));
continue;
}
}
}
else
{
// there might be the image without surrounding content control
image.RemoveNodes();
followingElement.Remove();
image.Add(followingElement);
continue;
}
// remove superflous paragraph from Image metadata
image.RemoveNodes();
// detach w:sdt from parent, and add to Image metadata
followingElement.Remove();
image.Add(followingElement);
}
int repeatDepth = 0;
int conditionalDepth = 0;
foreach (var metadata in xDoc.Descendants().Where(d =>
d.Name == PA.Repeat ||
d.Name == PA.Conditional ||
d.Name == PA.EndRepeat ||
d.Name == PA.EndConditional))
{
if (metadata.Name == PA.Repeat)
{
++repeatDepth;
metadata.Add(new XAttribute(PA.Depth, repeatDepth));
continue;
}
if (metadata.Name == PA.EndRepeat)
{
metadata.Add(new XAttribute(PA.Depth, repeatDepth));
--repeatDepth;
continue;
}
if (metadata.Name == PA.Conditional)
{
++conditionalDepth;
metadata.Add(new XAttribute(PA.Depth, conditionalDepth));
continue;
}
if (metadata.Name == PA.EndConditional)
{
metadata.Add(new XAttribute(PA.Depth, conditionalDepth));
--conditionalDepth;
continue;
}
}
while (true)
{
var didReplace = false;
foreach (var metadata in xDoc.Descendants().Where(d => (d.Name == PA.Repeat || d.Name == PA.Conditional || d.Name == PA.Image) && d.Attribute(PA.Depth) != null).ToList())
{
var depth = (int)metadata.Attribute(PA.Depth);
XName matchingEndName = null;
if (metadata.Name == PA.Repeat)
matchingEndName = PA.EndRepeat;
else if (metadata.Name == PA.Conditional)
matchingEndName = PA.EndConditional;
if (matchingEndName == null)
throw new OpenXmlPowerToolsException("Internal error");
var matchingEnd = metadata.ElementsAfterSelf(matchingEndName).FirstOrDefault(end => { return (int)end.Attribute(PA.Depth) == depth; });
if (matchingEnd == null)
{
metadata.ReplaceWith(CreateParaErrorMessage(string.Format("{0} does not have matching {1}", metadata.Name.LocalName, matchingEndName.LocalName), te));
continue;
}
metadata.RemoveNodes();
var contentBetween = metadata.ElementsAfterSelf().TakeWhile(after => after != matchingEnd).ToList();
foreach (var item in contentBetween)
item.Remove();
contentBetween = contentBetween.Where(n => n.Name != W.bookmarkStart && n.Name != W.bookmarkEnd).ToList();
metadata.Add(contentBetween);
metadata.Attributes(PA.Depth).Remove();
matchingEnd.Remove();
didReplace = true;
break;
}
if (!didReplace)
break;
}
}
private static List<string> s_AliasList = new List<string>
{
"Image",
"Content",
"Table",
"Repeat",
"EndRepeat",
"Conditional",
"EndConditional",
};
private static object TransformToMetadata(XNode node, XElement data, TemplateError te)
{
if (node is XElement element)
{
if (element.Name == W.sdt)
{
var alias = (string)element.Elements(W.sdtPr).Elements(W.alias).Attributes(W.val).FirstOrDefault();
if (string.IsNullOrEmpty(alias) || s_AliasList.Contains(alias))
{
var ccContents = element
.DescendantsTrimmed(W.txbxContent)
.Where(e => e.Name == W.t)
.Select(t => (string)t)
.StringConcatenate()
.Trim()
.Replace('“', '"')
.Replace('”', '"');
if (ccContents.StartsWith("<"))
{
var xml = TransformXmlTextToMetadata(te, ccContents);
if (xml.Name == W.p || xml.Name == W.r) // this means there was an error processing the XML.
{
if (element.Parent.Name == W.p)
return xml.Elements(W.r);
return xml;
}
if (alias != null && xml.Name.LocalName != alias)
{
if (element.Parent.Name == W.p)
return CreateRunErrorMessage("Error: Content control alias does not match metadata element name", te);
else
return CreateParaErrorMessage("Error: Content control alias does not match metadata element name", te);
}
xml.Add(element.Elements(W.sdtContent).Elements());
return xml;
}
return new XElement(element.Name,
element.Attributes(),
element.Nodes().Select(n => TransformToMetadata(n, data, te)));
}
return new XElement(element.Name,
element.Attributes(),
element.Nodes().Select(n => TransformToMetadata(n, data, te)));
}
if (element.Name == A.r)
{
var paraContents = element
.DescendantsTrimmed(W.txbxContent)
.Where(e => e.Name == A.t)
.Select(t => (string)t)
.StringConcatenate()
.Trim();
int occurances = paraContents.Select((c, i) => paraContents.Substring(i)).Count(sub => sub.StartsWith("<#"));
if (paraContents.StartsWith("<#") && paraContents.EndsWith("#>") && occurances == 1)
{
var xmlText = paraContents.Substring(2, paraContents.Length - 4).Trim();
var xml = TransformXmlTextToMetadata(te, xmlText);
if (xml.Name == W.p || xml.Name == W.r)
return xml;
xml.Add(element);
return xml;
}
if (paraContents.Contains("<#"))
{
var runReplacementInfo = new List<RunReplacementInfo>();
var thisGuid = Guid.NewGuid().ToString();
var r = new Regex("<#.*?#>");
XElement xml = null;
OpenXmlRegex.Replace(new[] { element }, r, thisGuid, (para, match) =>
{
var matchString = match.Value.Trim();
var xmlText = matchString.Substring(2, matchString.Length - 4).Trim().Replace('“', '"').Replace('”', '"');
try
{
xml = XElement.Parse(xmlText);
}
catch (XmlException e)
{
var rri = new RunReplacementInfo
{
Xml = null,
XmlExceptionMessage = "XmlException: " + e.Message,
SchemaValidationMessage = null,
};
runReplacementInfo.Add(rri);
return true;
}
var schemaError = ValidatePerSchema(xml);
if (schemaError != null)
{
var rri = new RunReplacementInfo
{
Xml = null,
XmlExceptionMessage = null,
SchemaValidationMessage = "Schema Validation Error: " + schemaError,
};
runReplacementInfo.Add(rri);
return true;
}
var rri2 = new RunReplacementInfo
{
Xml = xml,
XmlExceptionMessage = null,
SchemaValidationMessage = null,
};
runReplacementInfo.Add(rri2);
return true;
}, false);
var newPara = new XElement(element);
foreach (var rri in runReplacementInfo)
{
var runToReplace = newPara.Descendants(W.r).FirstOrDefault(rn => rn.Value == thisGuid && rn.Parent.Name != PA.Content);
if (runToReplace == null)
throw new OpenXmlPowerToolsException("Internal error");
if (rri.XmlExceptionMessage != null)
runToReplace.ReplaceWith(CreateRunErrorMessage(rri.XmlExceptionMessage, te));
else if (rri.SchemaValidationMessage != null)
runToReplace.ReplaceWith(CreateRunErrorMessage(rri.SchemaValidationMessage, te));
else
{
var newXml = new XElement(rri.Xml);
newXml.Add(runToReplace);
runToReplace.ReplaceWith(newXml);
}
}
var coalescedParagraph = WordprocessingMLUtil.CoalesceAdjacentRunsWithIdenticalFormatting(newPara);
return coalescedParagraph;
}
}
if (element.Name == W.p)
{
var paraContents = element
.DescendantsTrimmed(W.txbxContent)
.Where(e => e.Name == W.t)
.Select(t => (string)t)
.StringConcatenate()
.Trim();
var occurances = paraContents.Select((c, i) => paraContents.Substring(i)).Count(sub => sub.StartsWith("<#"));
if (paraContents.StartsWith("<#") && paraContents.EndsWith("#>") && occurances == 1)
{
var xmlText = paraContents.Substring(2, paraContents.Length - 4).Trim();
var xml = TransformXmlTextToMetadata(te, xmlText);
if (xml.Name == W.p || xml.Name == W.r)
return xml;
xml.Add(element);
return xml;
}
if (paraContents.Contains("<#"))
{
var runReplacementInfo = new List<RunReplacementInfo>();
var thisGuid = Guid.NewGuid().ToString();
var r = new Regex("<#.*?#>");
XElement xml = null;
OpenXmlRegex.Replace(new[] { element }, r, thisGuid, (para, match) =>
{
var matchString = match.Value.Trim();
var xmlText = matchString.Substring(2, matchString.Length - 4).Trim().Replace('“', '"').Replace('”', '"');
try
{
xml = XElement.Parse(xmlText);
}
catch (XmlException e)
{
var rri = new RunReplacementInfo
{
Xml = null,
XmlExceptionMessage = "XmlException: " + e.Message,
SchemaValidationMessage = null,
};
runReplacementInfo.Add(rri);
return true;
}
var schemaError = ValidatePerSchema(xml);
if (schemaError != null)
{
var rri = new RunReplacementInfo
{
Xml = null,
XmlExceptionMessage = null,
SchemaValidationMessage = "Schema Validation Error: " + schemaError,
};
runReplacementInfo.Add(rri);
return true;
}
var rri2 = new RunReplacementInfo
{
Xml = xml,
XmlExceptionMessage = null,
SchemaValidationMessage = null,
};
runReplacementInfo.Add(rri2);
return true;
}, false);
var newPara = new XElement(element);
foreach (var rri in runReplacementInfo)
{
var runToReplace = newPara.Descendants(W.r).FirstOrDefault(rn => rn.Value == thisGuid && rn.Parent.Name != PA.Content);
if (runToReplace == null)
throw new OpenXmlPowerToolsException("Internal error");
if (rri.XmlExceptionMessage != null)
runToReplace.ReplaceWith(CreateRunErrorMessage(rri.XmlExceptionMessage, te));
else if (rri.SchemaValidationMessage != null)
runToReplace.ReplaceWith(CreateRunErrorMessage(rri.SchemaValidationMessage, te));
else
{
var newXml = new XElement(rri.Xml);
newXml.Add(runToReplace);
runToReplace.ReplaceWith(newXml);
}
}
var coalescedParagraph = WordprocessingMLUtil.CoalesceAdjacentRunsWithIdenticalFormatting(newPara);
return coalescedParagraph;
}
}
return new XElement(element.Name,
element.Attributes(),
element.Nodes().Select(n => TransformToMetadata(n, data, te)));
}
return node;
}
private static XElement TransformXmlTextToMetadata(TemplateError te, string xmlText)
{
XElement xml;
try
{
xml = XElement.Parse(xmlText);
}
catch (XmlException e)
{
return CreateParaErrorMessage("XmlException: " + e.Message, te);
}
var schemaError = ValidatePerSchema(xml);
if (schemaError != null)
return CreateParaErrorMessage("Schema Validation Error: " + schemaError, te);
return xml;
}
private class RunReplacementInfo
{
public XElement Xml { get; set; }
public string XmlExceptionMessage { get; set; }
public string SchemaValidationMessage { get; set; }
}
private static string ValidatePerSchema(XElement element)
{
if (s_PASchemaSets == null)
{
s_PASchemaSets = new Dictionary<XName, PASchemaSet>
{
{
PA.Content,
new PASchemaSet
{
XsdMarkup =
@"<xs:schema attributeFormDefault='unqualified' elementFormDefault='qualified' xmlns:xs='http://www.w3.org/2001/XMLSchema'>
<xs:element name='Content'>
<xs:complexType>
<xs:attribute name='Select' type='xs:string' use='required' />
<xs:attribute name='Optional' type='xs:boolean' use='optional' />
</xs:complexType>
</xs:element>
</xs:schema>",
}
},
{
PA.Table,
new PASchemaSet
{
XsdMarkup =
@"<xs:schema attributeFormDefault='unqualified' elementFormDefault='qualified' xmlns:xs='http://www.w3.org/2001/XMLSchema'>
<xs:element name='Table'>
<xs:complexType>
<xs:attribute name='Select' type='xs:string' use='required' />
</xs:complexType>
</xs:element>
</xs:schema>",
}
},
{
PA.Repeat,
new PASchemaSet
{
XsdMarkup =
@"<xs:schema attributeFormDefault='unqualified' elementFormDefault='qualified' xmlns:xs='http://www.w3.org/2001/XMLSchema'>
<xs:element name='Repeat'>
<xs:complexType>
<xs:attribute name='Select' type='xs:string' use='required' />
<xs:attribute name='Optional' type='xs:boolean' use='optional' />
<xs:attribute name='Align' type='xs:string' use='optional' />
</xs:complexType>
</xs:element>
</xs:schema>",
}
},
{
PA.EndRepeat,
new PASchemaSet
{
XsdMarkup =
@"<xs:schema attributeFormDefault='unqualified' elementFormDefault='qualified' xmlns:xs='http://www.w3.org/2001/XMLSchema'>
<xs:element name='EndRepeat' />
</xs:schema>",
}
},
{
PA.Conditional,
new PASchemaSet
{
XsdMarkup =
@"<xs:schema attributeFormDefault='unqualified' elementFormDefault='qualified' xmlns:xs='http://www.w3.org/2001/XMLSchema'>
<xs:element name='Conditional'>
<xs:complexType>
<xs:attribute name='Select' type='xs:string' use='required' />
<xs:attribute name='Match' type='xs:string' use='optional' />
<xs:attribute name='NotMatch' type='xs:string' use='optional' />
</xs:complexType>
</xs:element>
</xs:schema>",
}
},
{
PA.EndConditional,
new PASchemaSet
{
XsdMarkup =
@"<xs:schema attributeFormDefault='unqualified' elementFormDefault='qualified' xmlns:xs='http://www.w3.org/2001/XMLSchema'>
<xs:element name='EndConditional' />
</xs:schema>",
}
},
{
PA.Image,
new PASchemaSet
{
XsdMarkup =
@"<xs:schema attributeFormDefault='unqualified' elementFormDefault='qualified' xmlns:xs='http://www.w3.org/2001/XMLSchema'>
<xs:element name='Image'>
<xs:complexType>
<xs:attribute name='Select' type='xs:string' use='required' />
</xs:complexType>
</xs:element>
</xs:schema>",
}
}
};
foreach (var item in s_PASchemaSets)
{
var itemPAss = item.Value;
var schemas = new XmlSchemaSet();
schemas.Add("", XmlReader.Create(new StringReader(itemPAss.XsdMarkup)));
itemPAss.SchemaSet = schemas;
}
}
if (!s_PASchemaSets.ContainsKey(element.Name))
{
return $"Invalid XML: {element.Name.LocalName} is not a valid element";
}
var paSchemaSet = s_PASchemaSets[element.Name];
var d = new XDocument(element);
string message = null;
d.Validate(paSchemaSet.SchemaSet, (sender, e) =>
{
message ??= e.Message;
}, true);
return message;
}
private class PA
{
public static readonly XName Image = "Image";
public static readonly XName Content = "Content";
public static readonly XName Table = "Table";
public static readonly XName Repeat = "Repeat";
public static readonly XName EndRepeat = "EndRepeat";
public static readonly XName Conditional = "Conditional";
public static readonly XName EndConditional = "EndConditional";
public static readonly XName Select = "Select";
public static readonly XName Optional = "Optional";
public static readonly XName Match = "Match";
public static readonly XName NotMatch = "NotMatch";
public static readonly XName Depth = "Depth";
public static readonly XName Align = "Align";
}
private class PASchemaSet
{
public string XsdMarkup { get; set; }
public XmlSchemaSet SchemaSet { get; set; }
}
private static Dictionary<XName, PASchemaSet> s_PASchemaSets;
private class TemplateError
{
public bool HasError { get; set; }
}
/// <summary>
/// Gets the next image relationship identifier of given part. The
/// parts can be either header, footer or main document part. The method
/// scans for already present relationship identifiers, then increments and
/// returns the next available value.
/// </summary>
/// <param name="part">The part.</param>
/// <returns>System.String.</returns>
private static string GetNextImageRelationshipId(OpenXmlPart part)
{
if (part is MainDocumentPart mainDocumentPart)
{
var imageId = mainDocumentPart.Parts
.Select(p => Regex.Match(p.RelationshipId, @"rId(?<rId>\d+)").Groups["rId"].Value)
.Max(Convert.ToDecimal);
return $"rId{++imageId}";
}
if (part is HeaderPart headerPart)
{
var imageId = headerPart.Parts
.Select(p => Regex.Match(p.RelationshipId, @"rId(?<rId>\d+)").Groups["rId"].Value)
.Max(Convert.ToDecimal);
return $"rId{++imageId}";
}
if (part is FooterPart footerPart)
{
var imageId = footerPart.Parts
.Select(p => Regex.Match(p.RelationshipId, @"rId(?<rId>\d+)").Groups["rId"].Value)
.Max(Convert.ToDecimal);
return $"rId{++imageId}";
}
return null;
}
/// <summary>
/// Calculates the maximum docPr id. The identifier is
/// unique throughout the document. This method
/// scans the whole document, finds and stores the max number (id is signed
/// 23 bit integer).
/// </summary>
/// <param name="wordDoc">The word document.</param>
/// <returns>System.Decimal.</returns>
private static decimal GetMaxDocPrId(WordprocessingDocument wordDoc)
{
var idsList = new List<string>();
foreach (var part in wordDoc.ContentParts())
{
idsList.AddRange(part.GetXDocument().Descendants(WP.docPr)
.SelectMany(e => e.Attributes().Where(a => a.Name == NoNamespace.id)).Select(v => v.Value));
}
return idsList.Count == 0 ? 0 : idsList.Max(Convert.ToDecimal);
}
private const string InvalidImageId = "InvalidImageId";
/// <summary>
/// Fixes docPrIds for the document. The identifier is unique throughout the
/// document. This method scans the whole document, finds and replaces the
/// image ids which were marked as invalid with incremental id
/// (id is signed 23 bit integer).
/// </summary>
/// <param name="wDoc">The word processing document.</param>
/// <param name="maxDocPrId">The current maximum document pr identifier calculated
/// before the document has been processed.</param>
private static void FixUpDocPrIds(WordprocessingDocument wDoc, decimal maxDocPrId)
{
var elementToFind = WP.docPr;
var docPrToChange = wDoc
.ContentParts()
.Select(cp => cp.GetXDocument())
.Select(xd => xd.Descendants().Where(d => d.Name == elementToFind))
.SelectMany(m => m);
var nextId = maxDocPrId;
foreach (var item in docPrToChange)
{
var idAtt = item.Attribute(NoNamespace.id);
if (idAtt != null && idAtt.Value == InvalidImageId)
idAtt.Value = $"{++nextId}";
}
foreach (var cp in wDoc.ContentParts())
cp.PutXDocument();
}
// shape type identifier
private static int s_shapeTypeId = 1;
private static int GetNextShapeType() => s_shapeTypeId++;
// shape identifier
private static int s_shapeId = 2000;
private static string GetNextShapeId() => $"_x0000_s{s_shapeId++}";
/// <summary>
/// Creates and returns the image part inside the given part. The
/// part can be either header, footer or main document part.
/// </summary>
/// <param name="part">The part.</param>
/// <param name="imagePartType">Type of the image part.</param>
/// <param name="relationshipId">The relationship identifier.</param>
/// <returns>ImagePart.</returns>
private static ImagePart GetImagePart(OpenXmlPart part, ImagePartType imagePartType, string relationshipId)
{
if (part is MainDocumentPart mainDocumentPart)
return mainDocumentPart.AddImagePart(imagePartType, relationshipId);
if (part is HeaderPart headerPart)
return headerPart.AddImagePart(imagePartType, relationshipId);
if (part is FooterPart footerPart)
return footerPart.AddImagePart(imagePartType, relationshipId);
return null;
}
/// <summary>
/// Method processes the image content and generates image element
/// </summary>
/// <param name="element">Source element</param>
/// <param name="data">Data element with content</param>
/// <param name="templateError">Error indicator</param>
/// <param name="part">The part where the image is getting processed.</param>
/// <returns>Image element</returns>
private static object ProcessImageContent(XElement element, XElement data, TemplateError templateError, OpenXmlPart part)
{
// check for misplaced sdt content, should contain the paragraph and not vice versa
var sdt = element.Descendants(W.sdt).FirstOrDefault();
// get the original element with all the formatting
var orig = sdt == null ? element.Descendants(W.p).FirstOrDefault() : sdt.Descendants(W.p).FirstOrDefault();
// check for first run having image element in it
if (orig == null || !orig.Descendants(W.r).FirstOrDefault().Descendants(W.drawing).Any())
{
return CreateContextErrorMessage(element, "Image metadata is not immediately followed by an image", templateError);
}
// clone the paragraph, so repeating elements won't be overridden
var para = new XElement(orig);
// get the xpath of of the element
var xPath = (string)element.Attribute(PA.Select);
// get image path
var imagePath = EvaluateXPathToString(data, xPath, false);
// assign unique image and paragraph ids. Image id is document property Id (wp:docPr)
// and relationship id is rId. Their numbering is different.
const string imageId = InvalidImageId; // Ids will be replaced with real ones later, after transform is done
var relationshipId = GetNextImageRelationshipId(part);
var inline =
para.Descendants(W.drawing)
.Descendants(WP.inline).FirstOrDefault();
if (inline == null)
{
return CreateContextErrorMessage(element, "Image: invalid picture control", templateError);
}
// get aspect ratio option
var ratioAttr = inline
.Descendants(WP.cNvGraphicFramePr)
.Descendants(A.graphicFrameLocks).FirstOrDefault().Attribute(NoNamespace.noChangeAspect);
var keepSourceImageAspect = (ratioAttr == null);
var keepOriginalImageSizeElement = inline.Descendants(Pic.cNvPicPr).FirstOrDefault();
var keepOriginalImageSize = false;
if (keepOriginalImageSizeElement != null)
{
var attr = keepOriginalImageSizeElement.Attribute("preferRelativeResize");
if (attr != null)
{
keepOriginalImageSize = attr.Value == "0";
}
}
// get extent
var extent = inline
.Descendants(WP.extent)
.FirstOrDefault();
var pictureExtent = inline
.Descendants(A.graphic)
.Descendants(A.graphicData)
.Descendants(Pic._pic)
.Descendants(Pic.spPr)
.Descendants(A.xfrm)
.Descendants(A.ext).
FirstOrDefault();
if (extent == null || pictureExtent == null)
{
return CreateContextErrorMessage(element, "Image: missing element in picture control - extent(s)", templateError);
}
// get docPr
var docPr = inline.Descendants(WP.docPr).FirstOrDefault();
if (docPr == null)
{
return CreateContextErrorMessage(element, "Image: missing element in picture control - docPtr", templateError);
}
docPr.SetAttributeValue(NoNamespace.id, imageId);
docPr.SetAttributeValue(NoNamespace.name, "Templated Image Content");
var blip = inline
.Descendants(A.graphic)
.Descendants(A.graphicData)
.Descendants(Pic.blipFill)
.Descendants(A.blip)
.FirstOrDefault();
if (blip != null)
{
// Add the image to main document part
var stream = Image2Stream(imagePath, out var imagePartType, out var error);
if (stream != null)
{
var ip = GetImagePart(part, imagePartType, relationshipId);
if (ip == null)
{
error = "Failed to get image part";
return CreateContextErrorMessage(element, string.Concat("Image: ", error), templateError);
}
ip.FeedData(stream);