public void WriteFile(string basedOn, string fn) { using (var templateDoc = WordprocessingDocument.Open(basedOn, false)) using (var resultDoc = WordprocessingDocument.Create(fn, WordprocessingDocumentType.Document)) { foreach (var part in templateDoc.Parts) { resultDoc.AddPart(part.OpenXmlPart, part.RelationshipId); } var body = resultDoc.MainDocumentPart.Document.Body; // We have to find the TOC, if one exists, and replace it... var tocFirst = -1; var tocLast = -1; var tocInstr = ""; var tocSec = null as Paragraph; if (FindToc(body, out tocFirst, out tocLast, out tocInstr, out tocSec)) { var tocRunFirst = new Run(new FieldChar { FieldCharType = FieldCharValues.Begin }, new FieldCode { Text = tocInstr, Space = SpaceProcessingModeValues.Preserve }, new FieldChar { FieldCharType = FieldCharValues.Separate }); var tocRunLast = new Run(new FieldChar { FieldCharType = FieldCharValues.End }); // for (int i = tocLast; i >= tocFirst; i--) { body.RemoveChild(body.ChildElements[i]); } var afterToc = body.ChildElements[tocFirst]; // for (int i = 0; i < Sections.Count; i++) { var section = Sections[i]; if (section.Level > 3) { continue; } var p = new Paragraph(); if (i == 0) { p.AppendChild(tocRunFirst); } p.AppendChild(new Hyperlink(new Run(new Text(section.Number + " " + section.Title))) { Anchor = section.BookmarkName }); if (i == Sections.Count - 1) { p.AppendChild(tocRunLast); } p.ParagraphProperties = new ParagraphProperties(new ParagraphStyleId { Val = $"TOC{section.Level}" }); body.InsertBefore(p, afterToc); } if (tocSec != null) { body.InsertBefore(tocSec, afterToc); } } var sectionDictionary = Sections.ToDictionary(sr => sr.Url); var maxBookmarkId = new StrongBox <int>(1 + body.Descendants <BookmarkStart>().Max(bookmark => int.Parse(bookmark.Id))); foreach (var src in Sources()) { var converter = new MarkdownConverter { mddoc = Markdown.Parse(src.Item2), filename = Path.GetFileName(src.Item1), wdoc = resultDoc, sections = sectionDictionary, maxBookmarkId = maxBookmarkId }; foreach (var p in converter.Paragraphs()) { body.AppendChild(p); } } } }