-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
508 lines (457 loc) · 17.5 KB
/
Program.cs
File metadata and controls
508 lines (457 loc) · 17.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
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using System.Xml;
using System.IO.Compression;
using Spire.Doc; // https://www.e-iceblue.com/Introduce/spire-office-for-net-free.html
using System.Data;
using System.Linq;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using System.Web;
using System.Text.Json;
using System.Net.Http;
using System.Threading.Tasks;
using QRCoder;
using System.Drawing;
using System.Drawing.Imaging;
using System.Diagnostics;
namespace FillDOCX
{
class Program
{
private static readonly Regex PLACEHOLDER = new Regex(@"@@(\w+)(?>\.(\w+))?", RegexOptions.Compiled | RegexOptions.IgnoreCase);
private static ushort _novalue = 0x0; // Keep track of novalue
private static string Fill(string template, XmlElement data, string novalue = "***", int level = 1)
{
if (data.Attributes.GetNamedItem("hidden") != null)
return "";
List<string> tags = new List<string>();
foreach (Match match in PLACEHOLDER.Matches(template))
{
if ((level == 1 || data.Name == match.Groups[1].Value) && !tags.Contains(match.Groups[level].Value))
tags.Add(match.Groups[level].Value);
}
tags.Sort((x, y) => y.Length.CompareTo(x.Length));
tags.ForEach(tag =>
{
XmlNodeList nodes = data.GetElementsByTagName(tag);
if (nodes.Count == 0)
nodes = data.GetElementsByTagName(tag.ToLower());
string subtemplate = level == 1 ? $"@@{tag}" : $"@@{data.Name}.{tag}", value = novalue;
_novalue |= 0x1;
if (nodes.Count > 0)
{
if (nodes[0].HasChildNodes && nodes[0].FirstChild.GetType() != typeof(System.Xml.XmlText) && level == 1)
{
subtemplate = new Regex(@"<w:tr (?:(?!<w:tr ).)*?@@" + Regex.Escape(tag) + @".*?<\/w:tr>", RegexOptions.Compiled).Match(template).Value;
if (subtemplate.IndexOf("</w:tr>") < subtemplate.Length - 7)
{
// subtemplate = new Regex(@"<w:t>@@" + Regex.Escape(tag) + @".*?<\/w:t>", RegexOptions.Compiled).Match(template).Value;
subtemplate = new Regex(@"<w:t>@@" + tag + @".*?<\/w:t>", RegexOptions.Compiled).Match(template).Value;
if (subtemplate == "")
return;
value += Fill(subtemplate, (XmlElement)nodes[0], novalue, level + 1);
}
else
{
foreach (XmlElement node in nodes)
value += Fill(subtemplate, node, novalue, level + 1);
}
}
else if (nodes[0].Attributes.GetNamedItem("hidden") != null)
{
value = "";
_novalue &= 0x2;
}
else
{
value = nodes[0].InnerXml;
_novalue &= 0x2;
}
}
if (Regex.Match(tag, @"^image\d+").Success)
value = "";
if (subtemplate != "")
{
if (value.IndexOf("altChunk") != -1)
value = HttpUtility.HtmlDecode(value);
value = Regex.Replace(value, @"&(lt;|gt;|quot;|apos;)", "&$1", RegexOptions.Multiline | RegexOptions.Compiled);
value = value.Replace("\\n", "<w:br/>");
value = value.Replace("\\/", "/");
template = template.Replace(subtemplate, value);
}
if ((_novalue & 0x1) == 0x1)
_novalue = 0x2;
});
return template;
}
private static readonly Regex USELESS = new Regex(@"</w:t></w:r><[\s\S]*?(<w:t>|<w:t [\s\S]*?>)(?<whitespace>.{1})", RegexOptions.Compiled | RegexOptions.IgnoreCase);
private static string Cleanup(string body)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(body);
int s = -2, sc;
MatchCollection matches = PLACEHOLDER.Matches(xmlDoc.InnerText);
foreach (Match match in matches.Cast<Match>())
{
string tag = match.Value;
sc = body.IndexOf("@</w:t>", s + 2); // Account for degenerate case, stand alone @ at end of a w:t run
s = body.IndexOf("@@", s + 2);
if (sc != -1 && sc < s)
s = sc;
int i = 0; // i to exit potential infinite loop
while (!body[s..].StartsWith(tag) && i < 10)
{
Match useless = USELESS.Match(body, s);
if (!useless.Success || useless.Value[13] == '/' || char.IsWhiteSpace(useless.Groups["whitespace"].Value, 0))
break;
body = body.Remove(useless.Index, useless.Length - 1);
++i;
}
}
xmlDoc = null;
// Rename all nested placeholders not within <w:tr ...</w:tr> to §§ preventing them from being processed in the next step by first replacing all @@ with §§, then restore the ones within <w:tr ...</w:tr> back to @@
body = Regex.Replace(body, @"@@(\w+\.\w+)", @"§§$1", RegexOptions.Compiled);
body = Regex.Replace(body, @"(<w:tr .*?§§\w+\.\w+.*?<\/w:tr>)", m => m.Value.Replace("§§", "@@"), RegexOptions.Compiled);
return body;
}
private static async Task<string> FillDOCX(string template, string mime, string txt, string destfile, string novalue, bool overwrite = false, bool pdf = false, bool shortTags = false, bool allowHTML = false, bool ignoreincomplete = false)
{
XmlDocument data = new XmlDocument();
data.PreserveWhitespace = true;
switch (mime)
{
case "application/xml":
try { data.Load(txt); } catch { data.LoadXml(txt); }
break;
case "application/json":
try
{
if (!Regex.IsMatch(txt, @"\s*[\[{]") && txt.IndexOfAny(Path.GetInvalidPathChars()) == -1)
{
if (txt.StartsWith("http"))
{
txt = await FetchDataAsync(txt);
}
else
{
using StreamReader sr = new StreamReader(txt);
txt = sr.ReadToEnd();
}
}
#if DEBUG
Console.Write(JsonToXml(txt));
#endif
data.LoadXml(JsonToXml(txt));
}
catch (SystemException e)
{
return String.Format("{0}: {1}", e.GetType().Name, e.Message);
}
break;
default:
try
{
throw new ArgumentException("Specify --xml or --json");
}
catch (SystemException e)
{
return String.Format("{0}: {1}", e.GetType().Name, e.Message);
}
}
try
{
if (template == destfile)
throw new ArgumentException("Template cannot be also the destination");
if (File.Exists(destfile) && !overwrite)
goto pdf; // return destfile;
if (Path.GetDirectoryName(destfile) != "")
Directory.CreateDirectory(Path.GetDirectoryName(destfile)); // Create directory if it does not exist
File.Copy(template, destfile, true);
// Search for HTML in XML and convert it into altChunks
if (allowHTML)
{
using WordprocessingDocument docWord = WordprocessingDocument.Open(destfile, true);
int altChunkId = 1;
MainDocumentPart mainPart = docWord.MainDocumentPart;
foreach (XmlNode node in data.SelectNodes("//text()"))
{
if (node.Value.IndexOf('<') == -1)
continue;
AlternativeFormatImportPart chunk = mainPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.Html, $"htmlChunk{altChunkId}");
using (Stream chunkStream = chunk.GetStream(FileMode.Create, FileAccess.Write))
using (StreamWriter stringStream = new StreamWriter(chunkStream))
stringStream.Write($"<html>{node.Value}</html>");
AltChunk altChunk = new AltChunk { Id = $"htmlChunk{altChunkId}" };
node.Value = $"<w:altChunk r:id=\"htmlChunk{altChunkId}\"/>";
mainPart.Document.Save();
++altChunkId;
}
}
FileStream destfileStream = File.Open(destfile, FileMode.Open);
using (ZipArchive zipArchive = new ZipArchive(destfileStream, ZipArchiveMode.Update))
{
ZipArchiveEntry zipFile;
String[] zipFiles = new String[] { @"word/document.xml", @"word/header1.xml", @"word/header2.xml", @"word/header3.xml", @"word/header4.xml", @"word/footer1.xml", @"word/footer2.xml", @"word/footer3.xml", @"word/footer4.xml" };
for (int i = 0; i < zipFiles.Length; ++i)
{
zipFile = zipArchive.GetEntry(zipFiles[i]);
if (zipFile == null)
continue;
StreamReader reader = new StreamReader(zipFile.Open());
string body = reader.ReadToEnd();
reader.Close();
zipFile.Delete();
// Short tags syntax @[0-9]+ convert to @@v[0-9]+
if (shortTags)
foreach (Match match in new Regex(@"@(\d*)(?:<\/w:t><\/w:r>.*?<w:t>)?(\d+)", RegexOptions.Compiled).Matches(body))
body = body.Replace(match.Value, @"@@v" + match.Groups[1].Value + match.Groups[2].Value);
else
body = Cleanup(body);
int limit = 0;
while (PLACEHOLDER.IsMatch(body) && limit < 10)
{
body = Fill(body, data.DocumentElement, novalue);
// Replace all §§ nested placeholders with corresponding XML first logical values
body = Regex.Replace(body, @"§§(\w+\.\w+)", m =>
{
string[] parts = m.Groups[1].Value.Split('.');
XmlNodeList nodes = data.GetElementsByTagName(parts[0]);
if (nodes.Count == 0)
nodes = data.GetElementsByTagName(parts[0].ToLower());
foreach (XmlElement node in nodes)
if (node.Name == parts[0] && node.Attributes.GetNamedItem("hidden") == null)
{
XmlNodeList subnodes = node.GetElementsByTagName(parts[1]);
if (subnodes.Count == 0)
subnodes = node.GetElementsByTagName(parts[1].ToLower());
if (subnodes.Count > 0 && subnodes[0].Attributes.GetNamedItem("hidden") == null)
return subnodes[0].InnerXml;
}
return novalue;
}, RegexOptions.Compiled);
// Remove [hidden]
int h = body.IndexOf("[hidden]"), s, e;
while (h != -1)
{
s = body.LastIndexOf("<w:tr ", h);
e = body.LastIndexOf("</w:tr>", h);
if (s == -1 || (s != -1 && s < e))
{ // [hidden] not wrapped inside <w:tr></w:tr>
s = body.LastIndexOf("<w:p ", h);
e = body.LastIndexOf("</w:p>", h);
if (s == -1 || (s != -1 && s < e)) // [hidden] not wrapped inside <w:p></w:p> just remove [hidden]
body = body.Remove(h, 8);
else // [hidden] wrapped inside <w:p></w:p> remove whole row
body = body.Remove(s, body.IndexOf("</w:p>", h) - s + 6);
}
else // [hidden] wrapped inside <w:tr></w:tr> remove whole row
body = body.Remove(s, body.IndexOf("</w:tr>", h) - s + 7);
h = body.IndexOf("[hidden]");
}
++limit;
}
zipFile = zipArchive.CreateEntry(zipFiles[i]);
StreamWriter writer = new StreamWriter(zipFile.Open());
writer.Write(body);
writer.Flush();
writer.Close();
}
Dictionary<ZipArchiveEntry, string> images = new Dictionary<ZipArchiveEntry, string>();
foreach (ZipArchiveEntry entry in zipArchive.Entries)
if (Regex.Match(entry.Name, @"^image\d+").Success)
{
string image = entry.Name[..entry.Name.IndexOf('.')];
XmlNodeList items = data.SelectNodes("//" + image + "|//" + image.ToUpper());
if (items.Count > 0 && (items[0].InnerText.StartsWith("qrcode://") || File.Exists(items[0].InnerText)))
images.Add(entry, items[0].InnerText);
}
foreach (KeyValuePair<ZipArchiveEntry, string> image in images)
{
if (image.Value.StartsWith("qrcode://"))
{
string qrCodePath = Path.Combine(Path.GetTempPath(), $"{image.Key.Name}.png");
// Generate QR code if the image file does not exist
using QRCoder.QRCodeGenerator qrGenerator = new QRCoder.QRCodeGenerator();
using QRCoder.QRCodeData qrCodeData = qrGenerator.CreateQrCode(image.Value.Substring(9), QRCoder.QRCodeGenerator.ECCLevel.Q);
using QRCoder.BitmapByteQRCode qrCode = new QRCoder.BitmapByteQRCode(qrCodeData);
using (MemoryStream ms = new MemoryStream(qrCode.GetGraphic(20)))
using (Bitmap qrCodeImage = new Bitmap(ms))
qrCodeImage.Save(qrCodePath, ImageFormat.Png);
zipArchive.CreateEntryFromFile(qrCodePath, image.Key.FullName);
File.Delete(qrCodePath); // Clean up the temporary QR code image
}
else
zipArchive.CreateEntryFromFile(image.Value, image.Key.FullName);
image.Key.Delete();
}
}
destfileStream.Close();
if ((_novalue & 0x2) == 0x2 && ignoreincomplete == false)
{
string incompletefile = destfile.Replace(".docx", "__.docx");
if (File.Exists(incompletefile))
File.Delete(incompletefile);
File.Move(destfile, incompletefile);
destfile = incompletefile;
}
}
catch (SystemException e)
{
return String.Format("{0}: {1}", e.GetType().Name, e.Message);
}
pdf:
return CreatePDF(destfile, pdf);
}
private static string CreatePDF(string destfile, bool pdf)
{
if (pdf)
{
// dotnet add package Spire.Doc
Spire.Doc.Document pdfDoc = new Spire.Doc.Document();
pdfDoc.LoadFromFile(destfile);
Spire.Doc.ToPdfParameterList parms = new Spire.Doc.ToPdfParameterList()
{
IsEmbeddedAllFonts = true
};
destfile = destfile.Replace(".docx", ".pdf");
pdfDoc.SaveToFile(destfile, parms);
pdfDoc.Close();
File.Delete(destfile.Replace(".pdf", ".docx"));
}
return destfile;
}
private static string JsonToXml(string json, string rootElement = "root")
{
try
{
using JsonDocument document = JsonDocument.Parse(json);
XmlDocument xmlDoc = new XmlDocument();
XmlElement root = xmlDoc.CreateElement(rootElement);
xmlDoc.AppendChild(root);
ConvertJsonToXml(document.RootElement, root, xmlDoc);
return xmlDoc.OuterXml;
}
catch (JsonException ex)
{
throw new ArgumentException("Invalid JSON format", ex);
}
}
private static void ConvertJsonToXml(JsonElement jsonElement, XmlElement parentElement, XmlDocument xmlDoc)
{
switch (jsonElement.ValueKind)
{
case JsonValueKind.Object:
foreach (JsonProperty property in jsonElement.EnumerateObject())
{
XmlElement childElement = xmlDoc.CreateElement(property.Name);
parentElement.AppendChild(childElement);
ConvertJsonToXml(property.Value, childElement, xmlDoc);
}
break;
case JsonValueKind.Array:
foreach (JsonElement arrayElement in jsonElement.EnumerateArray())
{
XmlElement arrayItem = xmlDoc.CreateElement("Item");
parentElement.AppendChild(arrayItem);
ConvertJsonToXml(arrayElement, arrayItem, xmlDoc);
}
break;
case JsonValueKind.String:
parentElement.InnerText = jsonElement.GetString();
break;
case JsonValueKind.Number:
parentElement.InnerText = jsonElement.GetRawText();
break;
case JsonValueKind.True:
case JsonValueKind.False:
parentElement.InnerText = jsonElement.GetBoolean().ToString();
break;
case JsonValueKind.Null:
// Leave the element empty for null values
break;
default:
throw new NotSupportedException($"Unsupported JSON value kind: {jsonElement.ValueKind}");
}
}
private static async Task<string> FetchDataAsync(string url)
{
using HttpClient client = new HttpClient();
try
{
return await client.GetStringAsync(url);
}
catch (HttpRequestException ex)
{
throw new Exception($"Error fetching data from URL: {url}", ex);
}
}
static async Task Main(string[] args)
{
string template = @".\template.docx", data = @".\data.xml", destfile = @"document.docx", novalue = @"***", mime = "application/xml", args_path = "";
bool overwrite = false, pdf = false, shorttags = false, allowhtml = false, ignoreincomplete = false;
try
{
for (int i = 0; i < args.Length; ++i)
{
if ((args[i] == "--template" || args[i] == "-t") && args[i + 1].EndsWith(".docx", StringComparison.InvariantCultureIgnoreCase)) // Case sensitive
template = args[++i];
else if (args[i] == "--xml" || args[i] == "-x")
{
mime = "application/xml";
data = args[++i];
}
else if (args[i] == "--json")
{
mime = "application/json";
data = args[++i];
}
else if ((args[i] == "--destfile" || args[i] == "-d") && args[i + 1].EndsWith(".docx", StringComparison.InvariantCultureIgnoreCase)) // Case sensitive
destfile = args[++i];
else if (args[i] == "--overwrite" || args[i] == "-o")
overwrite = true;
else if (args[i] == "--novalue")
novalue = i + 1 < args.Length ? args[++i] : "";
else if (args[i] == "--shorttags")
shorttags = true;
else if (args[i] == "--pdf")
pdf = true;
else if (args[i] == "--allowhtml")
allowhtml = true;
else if (args[i] == "--ignoreincomplete")
ignoreincomplete = true;
else
{
args_path = args[i];
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(args_path);
template = xmlDoc.SelectSingleNode(@"//template")?.InnerText;
data = xmlDoc.SelectSingleNode(@"//data")?.InnerText;
mime = xmlDoc.SelectSingleNode(@"//mime")?.InnerText;
destfile = xmlDoc.SelectSingleNode(@"//destfile")?.InnerText;
novalue = xmlDoc.SelectSingleNode(@"//novalue")?.InnerText;
overwrite = xmlDoc.SelectSingleNode(@"//overwrite")?.InnerText == "true";
shorttags = xmlDoc.SelectSingleNode(@"//shorttags")?.InnerText == "true";
pdf = xmlDoc.SelectSingleNode(@"//pdf")?.InnerText == "true";
allowhtml = xmlDoc.SelectSingleNode(@"//allowhtml")?.InnerText == "true";
ignoreincomplete = xmlDoc.SelectSingleNode(@"//ignoreincomplete")?.InnerText == "true";
xmlDoc = null;
}
}
}
catch (SystemException e)
{
if (e.HResult == -2146232000)
Console.WriteLine($"{e.Message} [${args_path}]");
else
Console.WriteLine(@"usage: filldocx [<args_path>] --template <path> (--xml|--json) (<path>|<url>|<raw>) --destfile <path> [--pdf] [--overwrite] [--shorttags] [--allowhtml] [--novalue <string>] [--ignoreincomplete]");
return;
}
// Await the asynchronous FillDOCX method
string result = await FillDOCX(template, mime, data, destfile, novalue, overwrite, pdf, shorttags, allowhtml, ignoreincomplete);
Console.WriteLine(result);
}
}
}