-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFormFiller.cs
More file actions
822 lines (726 loc) · 36.5 KB
/
FormFiller.cs
File metadata and controls
822 lines (726 loc) · 36.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
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
using System.Data;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using DocumentFormat.OpenXml;
namespace TRIS.FormFill.Lib
{
/// <summary>
/// Helper class for filling in data forms based on Word 2007 documents.
/// </summary>
public static class FormFiller
{
/// <summary>
/// Regex used to parse MERGEFIELDs in the provided document.
/// </summary>
private static readonly Regex instructionRegEx =
new Regex(
@"^[\s]*MERGEFIELD[\s]+(?<name>[#\w]*){1} # This retrieves the field's name (Named Capture Group -> name)
[\s]*(\\\*[\s]+(?<Format>[\w]*){1})? # Retrieves field's format flag (Named Capture Group -> Format)
[\s]*(\\b[\s]+[""]?(?<PreText>[^\\]*){1})? # Retrieves text to display before field data (Named Capture Group -> PreText)
# Retrieves text to display after field data (Named Capture Group -> PostText)
[\s]*(\\f[\s]+[""]?(?<PostText>[^\\]*){1})?",
RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.ExplicitCapture | RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace | RegexOptions.Singleline);
/// <summary>
/// Fills in a .docx file with the provided data.
/// </summary>
/// <param name="filename">Path to the template that must be used.</param>
/// <param name="dataset">Dataset with the datatables to use to fill the document tables with. Table names in the dataset should match the table names in the document.</param>
/// <param name="values">Values to fill the document. Keys should match the MERGEFIELD names.</param>
/// <returns>The filled-in document.</returns>
public static System.Xml.Linq.XElement GetWordReport(string filename, DataSet dataset, Dictionary<string, string> values, out string pages)
{
// first read document in as stream
byte[] original = File.ReadAllBytes(filename);
string[] switches = null;
System.Xml.Linq.XElement body = null;
//Body body = null;
using (MemoryStream stream = new MemoryStream())
{
stream.Write(original, 0, original.Length);
// Create a Wordprocessing document object.
using (WordprocessingDocument docx = WordprocessingDocument.Open(stream, true))
{
pages = docx.ExtendedFilePropertiesPart?.Properties.Pages.Text;
// 2010/08/01: addition
ConvertFieldCodes(docx.MainDocumentPart.Document);
#region first: process all tables
foreach (var field in docx.MainDocumentPart.Document.Descendants<SimpleField>())
{
string fieldname = GetFieldName(field, out switches);
if (!string.IsNullOrEmpty(fieldname) &&
fieldname.StartsWith("TBL_"))
{
TableRow wrow = GetFirstParent<TableRow>(field);
if (wrow == null)
{
continue; // can happen: is because table contains multiple fields, and after 1 pass, the initial row is already deleted
}
Table wtable = GetFirstParent<Table>(wrow);
if (wtable == null)
{
continue; // can happen: is because table contains multiple fields, and after 1 pass, the initial row is already deleted
}
string tablename = GetTableNameFromFieldName(fieldname);
if (dataset == null ||
!dataset.Tables.Contains(tablename) ||
dataset.Tables[tablename].Rows.Count == 0)
{
continue; // don't remove table here: will be done in next pass
}
DataTable table = dataset.Tables[tablename];
List<TableCellProperties> props = new List<TableCellProperties>();
List<string> cellcolumnnames = new List<string>();
List<string> paragraphInfo = new List<string>();
List<SimpleField> cellfields = new List<SimpleField>();
foreach (TableCell cell in wrow.Descendants<TableCell>())
{
props.Add(cell.GetFirstChild<TableCellProperties>());
Paragraph p = cell.GetFirstChild<Paragraph>();
if (p != null)
{
ParagraphProperties pp = p.GetFirstChild<ParagraphProperties>();
if (pp != null)
{
paragraphInfo.Add(pp.OuterXml);
}
else
{
paragraphInfo.Add(null);
}
}
else
{
paragraphInfo.Add(null);
}
string colname = string.Empty;
SimpleField colfield = null;
foreach (SimpleField cellfield in cell.Descendants<SimpleField>())
{
colfield = cellfield;
colname = GetColumnNameFromFieldName(GetFieldName(cellfield, out switches));
break; // supports only 1 cellfield per table
}
cellcolumnnames.Add(colname);
cellfields.Add(colfield);
}
// keep reference to row properties
TableRowProperties rprops = wrow.GetFirstChild<TableRowProperties>();
foreach (DataRow row in table.Rows)
{
TableRow nrow = new TableRow();
if (rprops != null)
{
nrow.Append(new TableRowProperties(rprops.OuterXml));
}
for (int i = 0; i < props.Count; i++)
{
TableCellProperties cellproperties = new TableCellProperties(props[i].OuterXml);
TableCell cell = new TableCell();
cell.Append(cellproperties);
Paragraph p = new Paragraph(new ParagraphProperties(paragraphInfo[i]));
cell.Append(p); // cell must contain at minimum a paragraph !
if (!string.IsNullOrEmpty(cellcolumnnames[i]))
{
if (!table.Columns.Contains(cellcolumnnames[i]))
{
throw new Exception(string.Format("Unable to complete template: column name '{0}' is unknown in parameter tables !", cellcolumnnames[i]));
}
if (!row.IsNull(cellcolumnnames[i]))
{
string val = row[cellcolumnnames[i]].ToString();
p.Append(GetRunElementForText(val, cellfields[i]));
}
}
nrow.Append(cell);
}
wtable.Append(nrow);
}
// finally : delete template-row (and thus also the mergefields in the table)
wrow.Remove();
}
}
#endregion
#region clean empty tables
foreach (var field in docx.MainDocumentPart.Document.Descendants<SimpleField>())
{
string fieldname = GetFieldName(field, out switches);
if (!string.IsNullOrEmpty(fieldname) &&
fieldname.StartsWith("TBL_"))
{
TableRow wrow = GetFirstParent<TableRow>(field);
if (wrow == null)
{
continue; // can happen: is because table contains multiple fields, and after 1 pass, the initial row is already deleted
}
Table wtable = GetFirstParent<Table>(wrow);
if (wtable == null)
{
continue; // can happen: is because table contains multiple fields, and after 1 pass, the initial row is already deleted
}
string tablename = GetTableNameFromFieldName(fieldname);
if (dataset == null ||
!dataset.Tables.Contains(tablename) ||
dataset.Tables[tablename].Rows.Count == 0)
{
// if there's a 'dt' switch: delete Word-table
if (switches.Contains("dt"))
{
wtable.Remove();
}
}
}
}
#endregion
// next : process all remaining fields in the main document
FillWordFieldsInElement(values, docx.MainDocumentPart.Document);
docx.MainDocumentPart.Document.Save(); // save main document back in package
// process header(s)
foreach (HeaderPart hpart in docx.MainDocumentPart.HeaderParts)
{
// 2010/08/01: addition
ConvertFieldCodes(hpart.Header);
FillWordFieldsInElement(values, hpart.Header);
hpart.Header.Save(); // save header back in package
}
// process footer(s)
foreach (FooterPart fpart in docx.MainDocumentPart.FooterParts)
{
// 2010/08/01: addition
ConvertFieldCodes(fpart.Footer);
FillWordFieldsInElement(values, fpart.Footer);
fpart.Footer.Save(); // save footer back in package
}
body = System.Xml.Linq.XElement.Parse(docx.MainDocumentPart.Document.Body.OuterXml);
//body = docx.MainDocumentPart.Document.Body;
}
stream.Close();
// get package bytes
//stream.Seek(0, SeekOrigin.Begin);
//byte[] data = stream.ToArray();
//return data;
}
return body;
}
//not used;
public static string GetWordReport2(string filename, Dictionary<string, string> values)
{
byte[] original = File.ReadAllBytes(filename);
string result;
using (var stream = new MemoryStream())
{
stream.Write(original, 0, original.Length);
using (var docx = WordprocessingDocument.Open(stream, true))
{
ConvertFieldCodes(docx.MainDocumentPart.Document);
FillWordFieldsInElement(values, docx.MainDocumentPart.Document);
docx.MainDocumentPart.Document.Save();
foreach (var hpart in docx.MainDocumentPart.HeaderParts)
{
ConvertFieldCodes(hpart.Header);
FillWordFieldsInElement(values, hpart.Header);
hpart.Header.Save();
}
foreach (var fpart in docx.MainDocumentPart.FooterParts)
{
ConvertFieldCodes(fpart.Footer);
FillWordFieldsInElement(values, fpart.Footer);
fpart.Footer.Save();
}
result = docx.MainDocumentPart.Document.Body.OuterXml;
docx.Close();
}
stream.Close();
}
return result;
}
/// <summary>
/// Applies any formatting specified to the pre and post text as
/// well as to fieldValue.
/// </summary>
/// <param name="format">The format flag to apply.</param>
/// <param name="fieldValue">The data value being inserted.</param>
/// <param name="preText">The text to appear before fieldValue, if any.</param>
/// <param name="postText">The text to appear after fieldValue, if any.</param>
/// <returns>The formatted text; [0] = fieldValue, [1] = preText, [2] = postText.</returns>
/// <exception cref="">Throw if fieldValue, preText, or postText are null.</exception>
internal static string[] ApplyFormatting(string format, string fieldValue, string preText, string postText)
{
string[] valuesToReturn = new string[3];
if ("UPPER".Equals(format))
{
// Convert everything to uppercase.
valuesToReturn[0] = fieldValue.ToUpper(CultureInfo.CurrentCulture);
valuesToReturn[1] = preText.ToUpper(CultureInfo.CurrentCulture);
valuesToReturn[2] = postText.ToUpper(CultureInfo.CurrentCulture);
}
else if ("LOWER".Equals(format))
{
// Convert everything to lowercase.
valuesToReturn[0] = fieldValue.ToLower(CultureInfo.CurrentCulture);
valuesToReturn[1] = preText.ToLower(CultureInfo.CurrentCulture);
valuesToReturn[2] = postText.ToLower(CultureInfo.CurrentCulture);
}
else if ("FirstCap".Equals(format))
{
// Capitalize the first letter, everything else is lowercase.
if (!string.IsNullOrEmpty(fieldValue))
{
valuesToReturn[0] = fieldValue.Substring(0, 1).ToUpper(CultureInfo.CurrentCulture);
if (fieldValue.Length > 1)
{
valuesToReturn[0] = valuesToReturn[0] + fieldValue.Substring(1).ToLower(CultureInfo.CurrentCulture);
}
}
if (!string.IsNullOrEmpty(preText))
{
valuesToReturn[1] = preText.Substring(0, 1).ToUpper(CultureInfo.CurrentCulture);
if (fieldValue.Length > 1)
{
valuesToReturn[1] = valuesToReturn[1] + preText.Substring(1).ToLower(CultureInfo.CurrentCulture);
}
}
if (!string.IsNullOrEmpty(postText))
{
valuesToReturn[2] = postText.Substring(0, 1).ToUpper(CultureInfo.CurrentCulture);
if (fieldValue.Length > 1)
{
valuesToReturn[2] = valuesToReturn[2] + postText.Substring(1).ToLower(CultureInfo.CurrentCulture);
}
}
}
else if ("Caps".Equals(format))
{
// Title casing: the first letter of every word should be capitalized.
valuesToReturn[0] = ToTitleCase(fieldValue);
valuesToReturn[1] = ToTitleCase(preText);
valuesToReturn[2] = ToTitleCase(postText);
}
else
{
valuesToReturn[0] = fieldValue;
valuesToReturn[1] = preText;
valuesToReturn[2] = postText;
}
return valuesToReturn;
}
/// <summary>
/// Executes the field switches on a given element.
/// The possible switches are:
/// <list>
/// <li>dt : delete table</li>
/// <li>dr : delete row</li>
/// <li>dp : delete paragraph</li>
/// </list>
/// </summary>
/// <param name="element">The element being operated on.</param>
/// <param name="switches">The switched to be executed.</param>
internal static void ExecuteSwitches(OpenXmlElement element, string[] switches)
{
if (switches == null || switches.Count() == 0)
{
return;
}
// check switches (switches are always lowercase)
if (switches.Contains("dp"))
{
Paragraph p = GetFirstParent<Paragraph>(element);
if (p != null)
{
p.Remove();
}
}
else if (switches.Contains("dr"))
{
TableRow row = GetFirstParent<TableRow>(element);
if (row != null)
{
row.Remove();
}
}
else if (switches.Contains("dt"))
{
Table table = GetFirstParent<Table>(element);
if (table != null)
{
table.Remove();
}
}
}
/// <summary>
/// Fills all the <see cref="SimpleFields"/> that are found in a given <see cref="OpenXmlElement"/>.
/// </summary>
/// <param name="values">The values to insert; keys should match the placeholder names, values are the data to insert.</param>
/// <param name="element">The document element taht will contain the new values.</param>
internal static void FillWordFieldsInElement(Dictionary<string, string> values, OpenXmlElement element)
{
string[] switches;
string[] options;
string[] formattedText;
Dictionary<SimpleField, string[]> emptyfields = new Dictionary<SimpleField, string[]>();
// First pass: fill in data, but do not delete empty fields. Deletions silently break the loop.
var list = element.Descendants<SimpleField>().ToArray();
foreach (var field in list)
{
string fieldname = GetFieldNameWithOptions(field, out switches, out options);
if (!string.IsNullOrEmpty(fieldname))
{
if (values.ContainsKey(fieldname)
&& !string.IsNullOrEmpty(values[fieldname]))
{
formattedText = ApplyFormatting(options[0], values[fieldname], options[1], options[2]);
// Prepend any text specified to appear before the data in the MergeField
if (!string.IsNullOrEmpty(options[1]))
{
field.Parent.InsertBeforeSelf<Paragraph>(GetPreOrPostParagraphToInsert(formattedText[1], field));
}
// Append any text specified to appear after the data in the MergeField
if (!string.IsNullOrEmpty(options[2]))
{
field.Parent.InsertAfterSelf<Paragraph>(GetPreOrPostParagraphToInsert(formattedText[2], field));
}
// replace mergefield with text
field.Parent.ReplaceChild<SimpleField>(GetRunElementForText(formattedText[0], field), field);
}
else
{
// keep track of unknown or empty fields
emptyfields[field] = switches;
}
}
}
// second pass : clear empty fields
foreach (KeyValuePair<SimpleField, string[]> kvp in emptyfields)
{
// if field is unknown or empty: execute switches and remove it from document !
ExecuteSwitches(kvp.Key, kvp.Value);
kvp.Key.Remove();
}
}
/// <summary>
/// Returns the columnname from a given fieldname from a Mergefield
/// The instruction of a table-Mergefield is formatted as TBL_tablename_columnname
/// </summary>
/// <param name="fieldname">The field name.</param>
/// <returns>The column name.</returns>
/// <exception cref="ArgumentException">Thrown when fieldname is not formatted as TBL_tablename_columname.</exception>
internal static string GetColumnNameFromFieldName(string fieldname)
{
// Column name is after the second underscore.
int pos1 = fieldname.IndexOf('_');
if (pos1 <= 0)
{
throw new ArgumentException("Error: table-MERGEFIELD should be formatted as follows: TBL_tablename_columnname.");
}
int pos2 = fieldname.IndexOf('_', pos1 + 1);
if (pos2 <= 0)
{
throw new ArgumentException("Error: table-MERGEFIELD should be formatted as follows: TBL_tablename_columnname.");
}
return fieldname.Substring(pos2 + 1);
}
/// <summary>
/// Returns the fieldname and switches from the given mergefield-instruction
/// Note: the switches are always returned lowercase !
/// </summary>
/// <param name="field">The field being examined.</param>
/// <param name="switches">An array of switches to apply to the field.</param>
/// <returns>The name of the field.</returns>
internal static string GetFieldName(SimpleField field, out string[] switches)
{
var a = field.GetAttribute("instr", "http://schemas.openxmlformats.org/wordprocessingml/2006/main");
switches = new string[0];
string fieldname = string.Empty;
string instruction = a.Value;
if (!string.IsNullOrEmpty(instruction))
{
Match m = instructionRegEx.Match(instruction);
if (m.Success)
{
fieldname = m.Groups["name"].ToString().Trim();
int pos = fieldname.IndexOf('#');
if (pos > 0)
{
// Process the switches, correct the fieldname.
switches = fieldname.Substring(pos + 1).ToLower().Split(new char[] { '#' }, StringSplitOptions.RemoveEmptyEntries);
fieldname = fieldname.Substring(0, pos);
}
}
}
return fieldname;
}
/// <summary>
/// Returns the fieldname and switches from the given mergefield-instruction
/// Note: the switches are always returned lowercase !
/// Note 2: options holds values for formatting and text to insert before and/or after the field value.
/// options[0] = Formatting (Upper, Lower, Caps a.k.a. title case, FirstCap)
/// options[1] = Text to insert before data
/// options[2] = Text to insert after data
/// </summary>
/// <param name="field">The field being examined.</param>
/// <param name="switches">An array of switches to apply to the field.</param>
/// <param name="options">Formatting options to apply.</param>
/// <returns>The name of the field.</returns>
internal static string GetFieldNameWithOptions(SimpleField field, out string[] switches, out string[] options)
{
var a = field.GetAttribute("instr", "http://schemas.openxmlformats.org/wordprocessingml/2006/main");
switches = new string[0];
options = new string[3];
string fieldname = string.Empty;
string instruction = a.Value;
if (!string.IsNullOrEmpty(instruction))
{
Match m = instructionRegEx.Match(instruction);
if (m.Success)
{
fieldname = m.Groups["name"].ToString().Trim();
options[0] = m.Groups["Format"].Value.Trim();
options[1] = m.Groups["PreText"].Value.Trim();
options[2] = m.Groups["PostText"].Value.Trim();
int pos = fieldname.IndexOf('#');
if (pos > 0)
{
// Process the switches, correct the fieldname.
switches = fieldname.Substring(pos + 1).ToLower().Split(new char[] { '#' }, StringSplitOptions.RemoveEmptyEntries);
fieldname = fieldname.Substring(0, pos);
}
}
}
return fieldname;
}
/// <summary>
/// Returns the first parent of a given <see cref="OpenXmlElement"/> that corresponds
/// to the given type.
/// This methods is different from the Ancestors-method on the OpenXmlElement in the sense that
/// this method will return only the first-parent in direct line (closest to the given element).
/// </summary>
/// <typeparam name="T">The type of element being searched for.</typeparam>
/// <param name="element">The element being examined.</param>
/// <returns>The first parent of the element of the specified type.</returns>
internal static T GetFirstParent<T>(OpenXmlElement element)
where T : OpenXmlElement
{
if (element.Parent == null)
{
return null;
}
else if (element.Parent.GetType() == typeof(T))
{
return element.Parent as T;
}
else
{
return GetFirstParent<T>(element.Parent);
}
}
/// <summary>
/// Creates a paragraph to house text that should appear before or after the MergeField.
/// </summary>
/// <param name="text">The text to display.</param>
/// <param name="fieldToMimic">The MergeField that will have its properties mimiced.</param>
/// <returns>An OpenXml Paragraph ready to insert.</returns>
internal static Paragraph GetPreOrPostParagraphToInsert(string text, SimpleField fieldToMimic)
{
Run runToInsert = GetRunElementForText(text, fieldToMimic);
Paragraph paragraphToInsert = new Paragraph();
paragraphToInsert.Append(runToInsert);
return paragraphToInsert;
}
/// <summary>
/// Returns a <see cref="Run"/>-openxml element for the given text.
/// Specific about this run-element is that it can describe multiple-line and tabbed-text.
/// The <see cref="SimpleField"/> placeholder can be provided too, to allow duplicating the formatting.
/// </summary>
/// <param name="text">The text to be inserted.</param>
/// <param name="placeHolder">The placeholder where the text will be inserted.</param>
/// <returns>A new <see cref="Run"/>-openxml element containing the specified text.</returns>
internal static Run GetRunElementForText(string text, SimpleField placeHolder)
{
string rpr = null;
if (placeHolder != null)
{
foreach (RunProperties placeholderrpr in placeHolder.Descendants<RunProperties>())
{
rpr = placeholderrpr.OuterXml;
break; // break at first
}
}
Run r = new Run();
if (!string.IsNullOrEmpty(rpr))
{
r.Append(new RunProperties(rpr));
}
if (!string.IsNullOrEmpty(text))
{
// first process line breaks
string[] split = text.Split(new string[] { "\n" }, StringSplitOptions.None);
bool first = true;
foreach (string s in split)
{
if (!first)
{
r.Append(new Break());
}
first = false;
// then process tabs
bool firsttab = true;
string[] tabsplit = s.Split(new string[] { "\t" }, StringSplitOptions.None);
foreach (string tabtext in tabsplit)
{
if (!firsttab)
{
r.Append(new TabChar());
}
r.Append(new Text(tabtext));
firsttab = false;
}
}
}
return r;
}
/// <summary>
/// Returns the table name from a given fieldname from a Mergefield.
/// The instruction of a table-Mergefield is formatted as TBL_tablename_columnname
/// </summary>
/// <param name="fieldname">The field name.</param>
/// <returns>The table name.</returns>
/// <exception cref="ArgumentException">Thrown when fieldname is not formatted as TBL_tablename_columname.</exception>
internal static string GetTableNameFromFieldName(string fieldname)
{
int pos1 = fieldname.IndexOf('_');
if (pos1 <= 0)
{
throw new ArgumentException("Error: table-MERGEFIELD should be formatted as follows: TBL_tablename_columnname.");
}
int pos2 = fieldname.IndexOf('_', pos1 + 1);
if (pos2 <= 0)
{
throw new ArgumentException("Error: table-MERGEFIELD should be formatted as follows: TBL_tablename_columnname.");
}
return fieldname.Substring(pos1 + 1, pos2 - pos1 - 1);
}
/// <summary>
/// Title-cases a string, capitalizing the first letter of every word.
/// </summary>
/// <param name="toConvert">The string to convert.</param>
/// <returns>The string after title-casing.</returns>
internal static string ToTitleCase(string toConvert)
{
return ToTitleCaseHelper(toConvert, string.Empty);
}
/// <summary>
/// Title-cases a string, capitalizing the first letter of every word.
/// </summary>
/// <param name="toConvert">The string to convert.</param>
/// <param name="alreadyConverted">The part of the string already converted. Seed with an empty string.</param>
/// <returns>The string after title-casing.</returns>
internal static string ToTitleCaseHelper(string toConvert, string alreadyConverted)
{
/*
* Tail-recursive title-casing implementation.
* Edge case: toConvert is empty, null, or just white space. If so, return alreadyConverted.
* Else: Capitalize the first letter of the first word in toConvert, append that to alreadyConverted and recur.
*/
if (string.IsNullOrEmpty(toConvert))
{
return alreadyConverted;
}
else
{
int indexOfFirstSpace = toConvert.IndexOf(' ');
string firstWord, restOfString;
// Check to see if we're on the last word or if there are more.
if (indexOfFirstSpace != -1)
{
firstWord = toConvert.Substring(0, indexOfFirstSpace);
restOfString = toConvert.Substring(indexOfFirstSpace).Trim();
}
else
{
firstWord = toConvert.Substring(0);
restOfString = string.Empty;
}
System.Text.StringBuilder sb = new StringBuilder();
sb.Append(alreadyConverted);
sb.Append(" ");
sb.Append(firstWord.Substring(0, 1).ToUpper(CultureInfo.CurrentCulture));
if (firstWord.Length > 1)
{
sb.Append(firstWord.Substring(1).ToLower(CultureInfo.CurrentCulture));
}
return ToTitleCaseHelper(restOfString, sb.ToString());
}
}
/// <summary>
/// Since MS Word 2010 the SimpleField element is not longer used. It has been replaced by a combination of
/// Run elements and a FieldCode element. This method will convert the new format to the old SimpleField-compliant
/// format.
/// </summary>
/// <param name="mainElement"></param>
internal static void ConvertFieldCodes(OpenXmlElement mainElement)
{
// search for all the Run elements
Run[] runs = mainElement.Descendants<Run>().ToArray();
if (runs.Length == 0) return;
Dictionary<Run, Run[]> newfields = new Dictionary<Run, Run[]>();
int cursor = 0;
do
{
Run run = runs[cursor];
if (run.HasChildren && run.Descendants<FieldChar>().Count() > 0
&& (run.Descendants<FieldChar>().First().FieldCharType & FieldCharValues.Begin) == FieldCharValues.Begin)
{
List<Run> innerRuns = new List<Run>();
innerRuns.Add(run);
// loop until we find the 'end' FieldChar
bool found = false;
string instruction = null;
RunProperties runprop = null;
do
{
cursor++;
run = runs[cursor];
innerRuns.Add(run);
if (run.HasChildren && run.Descendants<FieldCode>().Count() > 0)
instruction += run.GetFirstChild<FieldCode>().Text;
if (run.HasChildren && run.Descendants<FieldChar>().Count() > 0
&& (run.Descendants<FieldChar>().First().FieldCharType & FieldCharValues.End) == FieldCharValues.End)
{
found = true;
}
if (run.HasChildren && run.Descendants<RunProperties>().Count() > 0)
runprop = run.GetFirstChild<RunProperties>();
} while (found == false && cursor < runs.Length);
// something went wrong : found Begin but no End. Throw exception
if (!found)
throw new Exception("Found a Begin FieldChar but no End !");
if (!string.IsNullOrEmpty(instruction))
{
// build new Run containing a SimpleField
Run newrun = new Run();
if (runprop != null)
newrun.AppendChild(runprop.CloneNode(true));
SimpleField simplefield = new SimpleField();
simplefield.Instruction = instruction;
newrun.AppendChild(simplefield);
newfields.Add(newrun, innerRuns.ToArray());
}
}
cursor++;
} while (cursor < runs.Length);
// replace all FieldCodes by old-style SimpleFields
foreach (KeyValuePair<Run, Run[]> kvp in newfields)
{
kvp.Value[0].Parent.ReplaceChild(kvp.Key, kvp.Value[0]);
for (int i = 1; i < kvp.Value.Length; i++)
kvp.Value[i].Remove();
}
}
}
}