-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathDocxTemplateHelper.cs
67 lines (53 loc) · 2.1 KB
/
DocxTemplateHelper.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
using System.Reflection;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
namespace Markdig.Renderers.Docx;
public class DocxTemplateHelper
{
public static WordprocessingDocument Standard
{
get
{
var templateResource = "Markdig.Renderers.Docx.Resources.markdown-template.docx";
return LoadFromResource(templateResource, true);
}
}
public static WordprocessingDocument LoadFromResource(string templateResource, bool clean = false)
{
var stream = Assembly.GetExecutingAssembly()
.GetManifestResourceStream(templateResource);
if (stream == null)
{
stream = Assembly.GetCallingAssembly().GetManifestResourceStream(templateResource);
}
if (stream == null)
{
throw new FileNotFoundException($"Failed to load resource from {templateResource}");
}
var ms = new MemoryStream();
stream.CopyTo(ms);
var document = WordprocessingDocument.Open(ms, true);
if (clean)
{
CleanContents(document);
}
return document;
}
public static void CleanContents(WordprocessingDocument document)
{
document.MainDocumentPart!.Document.Body!.RemoveAllChildren();
if (document.MainDocumentPart?.NumberingDefinitionsPart?.Numbering != null)
{
document.MainDocumentPart.NumberingDefinitionsPart.Numbering.RemoveAllChildren<NumberingInstance>();
}
}
public static Paragraph? FindParagraphContainingText(WordprocessingDocument document, string text)
{
if (document.MainDocumentPart == null || document.MainDocumentPart.Document.Body == null) return null;
var textElement = document.MainDocumentPart.Document.Body
.Descendants<Text>().FirstOrDefault(t => t.Text.Contains(text));
if (textElement == null) return null;
var p = textElement.Ancestors<Paragraph>().FirstOrDefault();
return p;
}
}