/
OpenXmlExtensions.cs
351 lines (321 loc) · 12.4 KB
/
OpenXmlExtensions.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
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Wordprocessing;
using SP.Dto.Utilities;
using System;
using System.Collections.Generic;
using System.Linq;
namespace SP.Dto
{
public static class OpenXmlDocxExtensions
{
private const string _fieldTerminator = "\\*";
private const string _fieldBeforeText = "\\b";
private const string _fieldAfterText = "\\f";
public const string DocxMimeType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
private static readonly string[] _fieldCmds = new[] { _fieldTerminator, _fieldBeforeText, _fieldAfterText };
private const string _mergefield = "MERGEFIELD";
public static ILookup<string, OpenXmlElement> GetMergeFieldDict(this IEnumerable<OpenXmlElement> elements)
{
var allFields = elements.SelectMany(x => x.Descendants<SimpleField>().Select(sf => new { text = sf.Instruction.Value, el = (OpenXmlElement)sf })
.Concat(x.Descendants<FieldCode>().Select(fc => new { text = fc.Text, el = (OpenXmlElement)fc })));
return (from fc in allFields
let words = fc.text.TrimStart().Split(null,2)
where _mergefield.Equals(words.FirstOrDefault(), StringComparison.OrdinalIgnoreCase)
select new { text = words[1].FirstWord(), el= fc.el })
.ToLookup(k => k.text, v => v.el);
}
public static void CloneElement<T>(this OpenXmlElement cloneSource, IEnumerable<T> itemCollection, Func<string, T, string> withMergeField)
{
CloneElements(new[] { cloneSource }, itemCollection, (s, t, dummy) => withMergeField(s, t));
}
public static void RemoveAll(this IList<OpenXmlElement> elements)
{
foreach (var e in elements)
{
if (e.Parent != null)
{
e.Remove();
}
}
}
public static void CloneElements<T>(this IList<OpenXmlElement> cloneSource, IEnumerable<T> itemCollection, Func<string, T, IEnumerable<OpenXmlElement>, string> withMergeField)
{
IList<T> itemList = itemCollection as IList<T>;
if (itemList == null)
{
itemList = itemCollection.ToList();
}
if (itemList.Count == 0)
{
cloneSource.RemoveAll();
return;
}
var parent = cloneSource.First().Parent;
var followingSibling = cloneSource[cloneSource.Count-1].NextSibling();
/*
if (parent is TableRow)
{
parent = parent.FindFirstAncestor<Table>();
}
*/
var virginClonable = cloneSource.Select(c=>c.CloneNode(true)).ToList();
int lastRowIndex = itemList.Count - 1;
for (int i = 0; i < itemList.Count; i++)
{
var mergeFieldDict = cloneSource.GetMergeFieldDict();
foreach (var sf in mergeFieldDict)
{
string replaceVal = withMergeField(sf.Key.Replace(" ", string.Empty).Replace(".", string.Empty), itemList[i], sf);
if (replaceVal != null)
{
foreach (var s in sf)
{
InsertMergeFieldText(s, replaceVal);
}
}
}
if (i > 0) //on 1st run we are adjusting the current row, so no need to insert
{
foreach (var c in cloneSource)
{
if (followingSibling == null)
{
parent.AppendChild(c);
}
else
{
parent.InsertBefore(c, followingSibling);
}
}
}
if (i < lastRowIndex)
{
cloneSource = virginClonable.Select(c => c.CloneNode(true)).ToList();
}
else
{
cloneSource = virginClonable;
}
}
}
public static T FindFirstAncestor<T>(this OpenXmlElement element) where T : OpenXmlElement
{
T found = null;
while (found == null && element != null)
{
element = element.Parent;
found = element as T;
}
return found;
}
public static T FindFirstAncestor<T>(this OpenXmlElement element, out List<int> mapPositionsInHeirarchy) where T : OpenXmlElement
{
mapPositionsInHeirarchy = new List<int>();
T found = null;
while (found == null && element != null)
{
var parentElement = element.Parent;
mapPositionsInHeirarchy.Add(parentElement.ChildElements.IndexOf(element));
element = parentElement;
found = element as T;
}
mapPositionsInHeirarchy.Reverse();
return found;
}
public static OpenXmlElement NavigateIndexPath(this OpenXmlElement element, IEnumerable<int> descendentIndicies)
{
foreach (var indx in descendentIndicies)
{
element = element.ChildElements[indx];
}
return element;
}
private static Run CreateSimpleRun()
{
Run returnVar = new Run();
RunProperties runProp = new RunProperties();
runProp.Append(new NoProof());
returnVar.Append(runProp);
return returnVar;
}
private static Run CreateSimpleTextRun(string text)
{
var returnVar = CreateSimpleRun();
returnVar.Append(new Text() { Text = text });
return returnVar;
}
private static void InsertMergeFieldText(OpenXmlElement field, IList<string> listMembers)
{
var leafs = new List<OpenXmlLeafElement>(listMembers.Count);
foreach (var m in listMembers)
{
switch (m)
{
case "\n":
leafs.Add(new Break());
break;
case "\t":
leafs.Add(new TabChar());
break;
default:
leafs.Add(new Text(m));
break;
}
}
Run textRun;
//have to try and preserve formatting - therefore need to insert text into 1st run
var sf = field as SimpleField;
if (sf != null)
{
foreach (var l in leafs.OfType<Text>())
{
l.Text = InterpretFieldInstructions(l.Text, sf.Instruction);
}
var allTextRuns = sf.ChildElements<Run>().ToList(); ;
textRun = allTextRuns.GetTextRun();
if (textRun == null)
{
textRun = CreateSimpleRun();
sf.Append(textRun);
}
foreach (var r in allTextRuns.Where(ar=>ar != textRun))
{
r.Remove();
}
}
else
{
var fc = (FieldCode)field;
foreach (var l in leafs.OfType<Text>())
{
l.Text = InterpretFieldInstructions(l.Text, fc.InnerText);
}
var existingRuns = GetAssociatedRuns(fc);
var textRuns = existingRuns.Skip(2)
.SkipWhile(er => !er.ContainsCharType(FieldCharValues.Separate))
.Skip(1).ToList();
textRuns.RemoveAt(textRuns.Count - 1);
textRun = textRuns.GetTextRun();
if (textRun == null)
{
textRun = CreateSimpleRun();
var rEnd = existingRuns[existingRuns.Count - 1];
rEnd.InsertBeforeSelf(textRun);
}
foreach (var er in textRuns.Where(tr=>tr!= textRun))
{
er.Remove();
}
//fc.Append
}
textRun.ChildElementsNot<RunProperties>().ToList()
.ForEach(c=>c.Remove());
/*
if (leafs.Count == 0)
{
leafs.Add(new Text(string.Empty));
}
*/
textRun.Append(leafs);
}
private static string InterpretFieldInstructions(string str, string inst)
{
if (string.IsNullOrWhiteSpace(inst)) { return str; }
int instStart = inst.IndexOfWord(3);
int instFinish = inst.LastIndexOf(_fieldTerminator);
if (instStart == instFinish) { return str; }
inst = inst.Substring(instStart, instFinish - instStart);
bool after = false;
bool before = false;
foreach (var c in inst.SplitAndInclude(_fieldCmds))
{
switch (c)
{
case _fieldAfterText:
after = true;
break;
case _fieldBeforeText:
before = true;
break;
default:
if (after)
{
str += GetText(c);
after = false;
}
else if (before)
{
str = GetText(c) + str;
before = false;
}
break;
}
}
return str;
}
private static string GetText(string str)
{
str = str.Trim();
if (str[0] == '"')
{
str = str.Substring(1, str.Length - 2);
}
return str;
}
private static Run GetTextRun(this IEnumerable<Run> runs)
{
return runs.FirstOrDefault(er => !string.IsNullOrWhiteSpace(er.InnerText))
?? runs.FirstOrDefault(er => er.GetFirstChild<Text>() != null);
}
public static void InsertMergeFieldText(this OpenXmlElement field, string replacementText)
{
InsertMergeFieldText(field, replacementText.SplitAndInclude(new[] { '\t', '\n' }));
}
public static IList<Run> GetAssociatedRuns(this FieldCode fieldCode)
{
//adapted from http://stackoverflow.com/questions/8400152/how-can-i-put-a-content-in-a-mergefield-in-docx
Run rFieldCode = (Run)fieldCode.Parent;
Run rBegin = rFieldCode.PreviousSibling<Run>();
Run rCurrent = rFieldCode.NextSibling<Run>();
var runs = new List<Run>(new[] { rBegin, rFieldCode, rCurrent });
while (!rCurrent.ContainsCharType(FieldCharValues.End))
{
rCurrent = rCurrent.NextSibling<Run>();
runs.Add(rCurrent);
};
return runs;
}
public static IEnumerable<T> ChildElements<T>(this OpenXmlElement el) where T: OpenXmlElement
{
if (el.HasChildren)
{
var child = el.GetFirstChild<T>();
while (child != null)
{
yield return child;
child = child.NextSibling<T>();
}
}
}
public static IEnumerable<OpenXmlElement> ChildElementsNot<T>(this OpenXmlElement el) where T : OpenXmlElement
{
if (el.HasChildren)
{
foreach(var c in el.ChildElements)
{
if (c.GetType() != typeof(T))
{
yield return c;
}
}
}
}
public static bool ContainsCharType(this Run run, FieldCharValues fieldCharType)
{
var fc = run.GetFirstChild<FieldChar>();
return fc == null
? false
: fc.FieldCharType.Value == fieldCharType;
}
}
}