/
DocxDocumentBuilder.cs
174 lines (142 loc) · 5.47 KB
/
DocxDocumentBuilder.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
namespace TabulaRasa.Core.DocumentBuilder
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using Anchors;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Validation;
using DocumentFormat.OpenXml.Wordprocessing;
using Extensions;
using MetaObjects;
/// <summary>
/// Operates with content of tags and placeholders in OpenXML template
/// </summary>
public class DocxDocumentBuilder : DocxDocumentBuilderBase, IDocumentBuilder
{
private readonly DocxDocument docxDocument;
private readonly TagVisibilityOptions tagVisibilityOptions;
/// <summary>
/// Create builder for template
/// </summary>
/// <param name="docxDocument">Template document</param>
/// <param name="tagVisibilityOptions">List of tags for show and hide</param>
public DocxDocumentBuilder(DocxDocument docxDocument, TagVisibilityOptions tagVisibilityOptions = null)
: base(docxDocument.GetWordDocument())
{
this.docxDocument = docxDocument;
this.tagVisibilityOptions = tagVisibilityOptions;
MergeVanishedRuns();
}
/// <summary>
/// Factory method
/// </summary>
/// <param name="docxDocument">Template document</param>
public static IDocumentBuilder Create(DocxDocument docxDocument)
{
return new DocxDocumentBuilder(docxDocument);
}
public IDocumentBuilder Tag(string tagName, Action<IDocumentTagContextBuilder> options)
{
options(new DocxDocumentTagContextBuilder(Document, tagName));
return this;
}
public IDocumentBuilder Placeholder(string placeholderName, Action<IDocumentContextBuilder> options, bool preservePlaceholder = true)
{
var documentPlaceholders = DocumentPlaceholder.Get(Document, placeholderName);
foreach (var documentPlaceholder in documentPlaceholders)
ClearBetweenElements(documentPlaceholder.Opening, documentPlaceholder.Closing);
SaveDocument();
foreach (var documentPlaceholder in documentPlaceholders)
{
var builder = new DocxDocumentPlaceholderContextBuilder(Document, documentPlaceholders.Any() == false
? new RunProperties()
: documentPlaceholder.Opening.RunProperties);
options(builder);
foreach (var contentElement in builder.AggregatedContent)
documentPlaceholder.Closing.InsertBeforeSelf(contentElement.CloneElement());
if (preservePlaceholder == false)
documentPlaceholder.Remove();
}
SaveDocument();
return this;
}
public IDocumentBuilder BlockField(string fieldName, Action<IDocumentTagContextBuilder> options)
{
options(new DocxDocumentBlockFieldContextBuilder(Document, fieldName));
return this;
}
public IDocumentBuilder InlineField(string fieldName, Action<IDocumentContextBuilder> options)
{
var inlineFields = Anchors.InlineField.Get(Document, fieldName);
foreach (var inlineField in inlineFields)
inlineField.ContentWrapper.RemoveAllChildren();
SaveDocument();
foreach (var inlineField in inlineFields)
{
var builder = new DocxDocumentPlaceholderContextBuilder(Document, new RunProperties());
options(builder);
var cloned = builder.AggregatedContent
.Select(x => x.CloneElement())
.ToList();
var runs = cloned
.OfType<Run>();
foreach (var run in runs)
run.RunProperties = inlineField.RunProperties;
inlineField.ContentWrapper.Append(cloned);
}
SaveDocument();
return this;
}
public void SetVisibilityTag(string tagName, bool visible)
{
docxDocument.SetTagVisibility(tagName, visible);
}
public bool Validate()
{
var errorInfos = new OpenXmlValidator(FileFormatVersions.Office2007).Validate(Document);
return !errorInfos.Any();
}
public string GetCustomProperty(string key)
{
return docxDocument.GetCustomProperty(key);
}
public IEnumerable<Field> Fields
{
get { return docxDocument.Fields; }
}
public byte[] ToArray()
{
if (tagVisibilityOptions != null)
docxDocument.SetTagVisibility(tagVisibilityOptions);
return docxDocument.ToArray();
}
private void MergeVanishedRuns()
{
var vanishedRuns = Document.MainDocumentPart.Document.Descendants().OfType<Run>()
.Where(SplittedRunPredicate).ToList();
var vanishedNeighbours = new List<List<Run>>();
foreach (var vanishedRun in vanishedRuns)
if (!vanishedNeighbours.Any() || vanishedNeighbours.Last().Last().NextSibling<Run>() != vanishedRun)
vanishedNeighbours.Add(new List<Run> {vanishedRun});
else
vanishedNeighbours.Last().Add(vanishedRun);
vanishedNeighbours.Where(x => x.Count > 1)
.ToList()
.ForEach(x =>
{
x.First()
.OfType<Text>()
.Last().Text = x.Aggregate(string.Empty, (a, c) => a + c.InnerText);
x.RemoveAt(0);
x.ForEach(z => z.Remove());
});
}
private static bool SplittedRunPredicate(Run run)
{
var placeholderRegex = new Regex(@"{{/?.+}}");
return run.RunProperties != null && run.RunProperties.Vanish != null && placeholderRegex.IsMatch(run.InnerText) == false;
}
}
}