OfficeIMO.Word
May 29, 2026 · View on GitHub
OfficeIMO.Word is a cross‑platform .NET library for creating and editing Microsoft Word (.docx) documents on top of Open XML.
- Targets: netstandard2.0, net472 (Windows build), net8.0, net10.0
- License: MIT
- NuGet:
OfficeIMO.Word - Dependencies: DocumentFormat.OpenXml, OfficeIMO.Drawing
AOT / Trimming notes
- Core Word APIs avoid private reflection; converters are AOT‑aware.
- Macro removal uses OpenXmlPackage reflection and is annotated for trimming.
Quick starts and runnable samples live in OfficeIMO.Examples/Word/*.
Install
dotnet add package OfficeIMO.Word
Hello, Word
using OfficeIMO.Word;
using var doc = WordDocument.Create("example.docx");
var p = doc.AddParagraph("Hello OfficeIMO.Word");
p.SetBold();
doc.Sections[0].Headers.Default.AddParagraph("Header");
doc.Sections[0].Footers.Default.AddParagraph("Page ");
doc.Sections[0].Footers.Default.AddPageNumber();
doc.Save();
Encrypted Documents
using var doc = WordDocument.Create("secure.docx");
doc.AddParagraph("Confidential");
doc.SaveEncrypted("secure.docx", "secret");
using var reopened = WordDocument.LoadEncrypted("secure.docx", "secret");
Common Tasks by Example
Paragraphs and runs
var p = doc.AddParagraph("Title");
p.SetBold();
p = doc.AddParagraph("Body text");
p.AddText(" with italic").SetItalic();
p.AddText(" and code").SetFontFamily("Consolas");
Tables
var t = doc.AddTable(3, 3);
t[1,1].Text = "Header 1"; t[1,2].Text = "Header 2"; t[1,3].Text = "Header 3";
t.HeaderRow = true; t.Style = WordTableStyle.TableGrid;
t.MergeCells(2,1, 2,3); // row 2, col 1..3
Images
var imgP = doc.AddParagraph();
imgP.AddImage("logo.png", width: 96, height: 32);
Headers, footers, and page numbers
var sec = doc.Sections[0];
sec.Headers.Default.AddParagraph("Report");
var f = sec.Footers.Default;
f.AddParagraph().AddText("Page ");
f.AddPageNumber();
Hyperlinks
doc.AddParagraph().AddHyperLink("OpenAI", new Uri("https://openai.com/"));
Append another document
using var destination = WordDocument.Load("report-main.docx");
using var appendix = WordDocument.Load("report-appendix.docx");
destination.AppendDocument(appendix);
destination.SaveAs("report-merged.docx");
Sample: OfficeIMO.Examples/Word/MergeDocuments/MergeDocuments.Basic.cs
Fields
var para = doc.AddParagraph();
var field = para.AddField(WordFieldType.Date, wordFieldFormat: WordFieldFormat.ShortDate);
Mail Merge (MERGEFIELD)
var para2 = doc.AddParagraph();
// Simple MERGEFIELD with a custom format
para2.AddField(WordFieldType.MergeField, customFormat: "CustomerName");
// Advanced builder for complex instructions/switches
var builder = new WordFieldBuilder(WordFieldType.MergeField)
.CustomFormat("OrderTotal")
.Format(WordFieldFormat.Numeric);
para2.AddField(builder);
Footnotes / Endnotes
var r = doc.AddParagraph("See note").AddText(" ");
r.AddFootNote("This is a footnote.");
Content controls
var sdtPara = doc.AddParagraph("Name: ");
var dd = sdtPara.AddDropDownList(new[]{"Alpha","Beta","Gamma"});
doc.FillContentControlValues(new Dictionary<string, object?> {
["Name"] = "Ada Lovelace",
["Approved"] = true,
["DueDate"] = DateTime.Today,
["Status"] = "Beta"
});
Dictionary<string, object?> values = doc.ExtractContentControlValues();
doc.ValidateContentControlValues(values).EnsureValid();
Shapes and charts (basic)
var shp = doc.AddShape(ShapeTypeValues.Rectangle, 150, 50);
shp.FillColorHex = "#E7FFE7"; shp.StrokeColorHex = "#008000";
var ch = doc.AddChart(ChartType.Bar, 400, 250);
ch.AddSeries("S1", new[]{1,3,2});
ch.AddLegend(LegendPositionValues.Right);
ch.SetXAxisTitle("Categories");
ch.SetYAxisTitle("Values");
Watermarks
doc.SetTextWatermark("CONFIDENTIAL", opacity: 0.15);
Protection
doc.ProtectDocument(enforce: true, password: "secret");
Table of Contents (TOC)
// Add headings (styles must map to heading levels)
doc.AddParagraph("Chapter 1").SetStyle("Heading1");
doc.AddParagraph("Section 1.1").SetStyle("Heading2");
// Insert TOC near the top (field will update on open)
doc.Paragraphs[0].AddField(WordFieldType.TOC);
Converters — HTML / Markdown / PDF
// HTML
using OfficeIMO.Word.Html;
var html = WordHtmlConverter.ToHtml(doc);
var doc2 = WordHtmlConverter.FromHtml("<h1>Hi</h1><p>Generated</p>");
// Markdown
using OfficeIMO.Word.Markdown;
var md = WordMarkdownConverter.ToMarkdown(doc);
var doc3 = WordMarkdownConverter.FromMarkdown("# Title\nBody");
// PDF
using OfficeIMO.Word.Pdf;
doc.SaveAsPdf("out.pdf");
HTML via Markdown (OfficeIMO.Markdown)
using OfficeIMO.Word.Markdown; // also uses OfficeIMO.Markdown under the hood
// Full HTML document or embeddable fragment produced via Markdown pipeline
var htmlDoc = doc.ToHtmlViaMarkdown();
var htmlFrag = doc.ToHtmlFragmentViaMarkdown();
// Save to file (supports external CSS sidecar via HtmlOptions)
doc.SaveAsHtmlViaMarkdown("report.html");
Fluent API Shortcuts
Common shortcuts for composing content:
H1..H6(string)— adds styled heading paragraphsP(string)— adds a plain paragraphUl(Action<ListBuilder>)— bulleted list; supports.Item,.ItemLink,.ItemTaskOl(Action<ListBuilder>)— numbered list; supports.Item,.ItemLinkParagraph(pb => pb.Text/Link/Bold/Italic/Underline/Strike/Code/InlineImage(...))— inline helpersTable(tb => tb.Headers(...).Row(...).Rows(...))— convenience wrappers
Example
using OfficeIMO.Word.Fluent;
var fluent = new WordFluentDocument(doc)
.H1("Report")
.P("All‑in‑one DNS/TLS report.")
.Ul(ul => ul.Item("SPF/DKIM/DMARC").ItemLink("Docs", "https://evotec.xyz"))
.Ol(ol => ol.Item("Step one").Item("Step two"))
.Paragraph(p => p.Bold("Note:").Text(" Works with Markdown too."));
Feature Highlights
- Document: create/load/save, clean/repair, compatibility settings, protection, append/merge other
.docxfiles - Sections: margins, size/orientation, columns, headers/footers (first/even/odd)
- Paragraphs/Runs: bold/italic/underline/strike, shading, tabs, breaks, justification
- Tables: create, merge/split, borders/shading, widths, header row repeat, page breaks
- Images: add from file/stream/base64/URL, wrap/layout, crop/opacity/flip/rotate, position
- Hyperlinks: internal/external with tooltip/target
- Fields: add/read/remove/update (DATE, TOC, PAGE, MERGEFIELD, etc.)
- Footnotes/Endnotes: add/read/remove
- Bookmarks/Cross‑references: add/read/remove
- Content controls (SDT): checkbox/date/dropdown/combobox/picture/repeating section
- Shapes/SmartArt: basic shapes with fill/stroke; SmartArt detection
- Charts: pie/bar/line/combo/scatter/area/radar with axes, legends, multiple series
- Styles: paragraph/run styles, borders, shading
Explore
OfficeIMO.Examples/Word/*for complete scenarios.
Detailed Feature Matrix
- 📄 Documents
- ✅ Create/Load/Save, SaveAs (sync/async); clean & repair
- ✅ Compatibility settings; document variables; protection (read‑only recommended/final/enforced)
- ⚠️ Digital signatures (basic scenarios); ✅ macros (add/extract/remove modules)
- 📑 Sections & Page Setup
- ✅ Orientation, paper size, margins, columns
- ✅ Headers/footers (default/even/first), page breaks, repeating table header rows, background color
- ✍️ Paragraphs & Runs
- ✅ Styles (paragraph/run); bold/italic/underline/strike; shading; alignment; indentation; line spacing; tabs/tab stops
- ✅ Find/replace helpers
- 🧱 Tables
- ✅ Create/append; built‑in styles (105); borders/shading; widths; merge/split (H/V); nested tables
- ✅ Row heights and page‑break control; merged‑cell detection
- 🖼️ Images
- ✅ From file/stream/base64/URL; alt text
- ✅ Size (px/pt/EMU); wrap/layout; crop; transparency; flip/rotate; position; read/write EMU sizes
- 🔗 Links & Bookmarks
- ✅ External/internal hyperlinks (tooltip/target); bookmarks; cross‑references
- 🧾 Fields
- ✅ Add/read/remove/update (DATE, PAGE, NUMPAGES, TOC, MERGEFIELD, …)
- ✅ Simple and advanced representations; custom formats
- 📝 Notes
- ✅ Footnotes and endnotes: add/read/remove
- 🧩 Content Controls (SDT)
- ✅ Checkbox, date picker, dropdown, combobox, picture, repeating section
- ✅ Form-map fill/extraction and preflight validation for text, checkbox, date picker, dropdown, combobox, picture controls, repeating-section item text, and ambiguous tag/alias keys
- 📊 Charts
- ✅ Pie/Bar/Line/Combo/Scatter/Area/Radar; axes/legends/series; axis titles
- ⚠️ Formatting depth varies by chart type
- 🔷 Shapes/SmartArt
- ✅ Basic AutoShapes with fill/stroke; ⚠️ SmartArt detection/limited operations
Dependencies & Versions
- DocumentFormat.OpenXml: range
[3.5.1, 4.0.0) - OfficeIMO.Drawing: shared first-party color and image metadata helpers
- License: MIT
Converters (adjacent packages)
- HTML:
OfficeIMO.Word.Html(AngleSharp) — convert to/from HTML - Markdown:
OfficeIMO.Word.Markdown— convert to/from Markdown using OfficeIMO.Markdown - PDF:
OfficeIMO.Word.Pdf(QuestPDF/SkiaSharp) — export to PDF
Note: Converters ship as adjacent packages so consumers can opt into the extra dependency surface only when needed.
Notes on Versioning
- Minor releases may include additive APIs and perf improvements.
- Patch releases fix bugs and compatibility issues without breaking APIs.
Notes
- Cross‑platform: no COM automation, no Office required.
- Deterministic save order to keep Excel/Word “file repair” dialogs at bay.
- Nullable annotations enabled; APIs strive to be safe and predictable.