md-reports
Convert Markdown to DOCX using a configurable Word template. Designed for embedding in Python scripts (no CLI). Extensible to other output formats.
Install
uv add md-reports
Quick start
from md_reports import convert_markdown_text, convert_markdown_file
# from a string
convert_markdown_text(
"# Title\n\nHello **world**.",
"out.docx",
)
# from a file (relative image paths resolve against the markdown file)
convert_markdown_file("doc.md", "doc.docx")
# inject script values via Jinja2 substitution
convert_markdown_text(
"# Q{{ q }} report\n\nRevenue grew by **{{ pct }}%**.",
"report.docx",
context={"q": 2, "pct": 14.5},
)
Reusable converter (avoids reloading the template each call; supports
a default_context shared across all conversions):
from md_reports import (
ConversionOptions, DocxRenderer, MarkdownConverter,
)
conv = MarkdownConverter(
renderer=DocxRenderer(
template_path="house_style.docx",
options=ConversionOptions(strict_mode=True),
),
default_context={"site": "Acme"},
)
conv.convert_file("a.md", "a.docx", context={"doc": "Q1"})
conv.convert_file("b.md", "b.docx", context={"doc": "Q2"})
The renderer argument selects the output format. DocxRenderer is
the only built-in renderer today; the abstraction is in place for
additional renderers (e.g. HTML) to be added without changes to
parse, the model, options, or MarkdownConverter.
What's supported
Block elements:
- Headings
#to######(mapped toHeading 1…Heading 6with cascading fallback) - Paragraphs, block quotes, fenced code blocks
- Bullet and ordered lists (with nesting)
- Standard markdown tables (header + body rows, alignment markers)
- CSV embedding via fenced blocks — both file-backed and inline literal data
- Embedded images (
) as figures with auto-numbered captions - LaTeX math expressions rendered as native, editable Word equations
(inline
$…$and display$$…$$)
Inline elements: bold, italic, inline code, markdown links, minimal
inline <a href="...">…</a> HTML, and inline math ($…$).
Figures
Block-level images become a figure with an auto-numbered caption sourced from the alt text:

renders the image followed by a Caption-styled paragraph
Figure 1: Quarterly revenue chart. The number is a Word SEQ field,
so it stays correct after copy/paste or reordering (Word updates fields
on print or F9).
Table captions
Markdown has no native table caption syntax. md-reports consumes the
paragraph immediately preceding a table when it begins with Table::
Table: Quarterly revenue by region.
| Region | Q1 | Q2 |
|--------|----|----|
| EMEA | 1 | 2 |
The caption is emitted above the table as
Table 1: Quarterly revenue by region. styled with Caption. Figure and
table counters are independent. The prefix is configurable via
ConversionOptions.table_caption_prefix.
Cross-references
Attach a label to a figure or table by appending {#label} to its alt
text or caption, then refer to it from anywhere in the document with a
markdown link whose target is #label:

Table: Sales by region {#tab-sales}
| Region | Total |
|--------|------:|
| EMEA | 100 |
See [Figure 1](#fig-revenue) and [](#tab-sales) for details.
Each labelled caption is wrapped in a Word bookmark; each #label link
becomes a Word REF field pointing at that bookmark. The link text
becomes the cached display value; an empty link text auto-fills as
"<Prefix> <Number>" (e.g. Table 1, or Table 2-1 with
chapter-numbered captions). Forward
references work — the
parser resolves all labels before rendering. After F9 (or print), Word
recomputes both the SEQ counters and the REF fields so reordering or
inserting figures keeps numbering and cross-references in sync.
Unknown #label targets degrade to plain text with a warning (or raise
in strict_mode). Auto-filled reference text always matches the
number the caption actually received; if a labelled figure or table
fails to render (e.g. a missing image), references to it warn (or
raise in strict_mode).
Preview-friendly label form
The bare {#label} marker shows up as literal text when the markdown
is viewed in a plain markdown previewer (GitHub, VS Code, etc.). For
table and CSV captions you can wrap the marker in an HTML comment so
the marker is invisible in previews while still being picked up by
md-reports:
Table: Sales by region <!-- {#tab-sales} -->
| Region | Total |
|--------|------:|
| EMEA | 100 |
Both forms are supported and behave identically; pick whichever you prefer. The comment must come at the end of the caption. Image alt text is already invisible in previews, so the bare form is fine there and no comment variant is needed.
Chapter-numbered captions
By default captions are numbered through the whole document
(Figure 1, Figure 2, …). Set caption_chapter_level to number
them per chapter instead, as Word's Insert Caption → Include chapter
number does:
from md_reports import ConversionOptions, convert_markdown_file
convert_markdown_file(
"report.md",
"report.docx",
options=ConversionOptions(
caption_chapter_level=1, # chapters are `#` headings
caption_chapter_separator=".", # Figure 2.3 (default "-")
),
)
- Headings at the chapter level start a new chapter, and the figure
and table counters restart at every heading at that level or above.
With
caption_chapter_level=2, captions readFigure 1.2-3. - The chapter number comes from Word's own heading numbering (a
STYLEREFfield), so the chapter headings are numbered in the output (1 Introduction,1.1 Background). If the template's heading styles have no numbering, simple1/1.1numbering is added to the output document (the template file is not changed). A template that already numbers its headings is used as is. - Because headings are numbered automatically, don't type numbers into
heading text, and don't use
#for the document title when chapters are#headings — put the title in the template's title block (see Front matter) or usecaption_chapter_level=2. - A caption before the first chapter heading, or (at level 2 and
deeper) under a higher heading before its first chapter heading,
repeats another caption's number in Word. Both warn, or raise in
strict_mode. - Cached numbers match what Word computes. Templates whose heading numbering is not plain decimal starting at 1 (e.g. roman numerals) warn that the cached values may differ until fields are updated (Ctrl+A, F9). A template that numbers only some of the heading levels up to the chapter level warns and keeps document-wide numbering.
CSV embedding
Two fenced-block variants render CSV data as a DOCX table.
From a file — the body is a single path resolved against
project_root (or the markdown file's directory):
Table: Quarterly revenue.
```csv-file
data/quarterly.csv
```
Inline — the body is the CSV literal itself:
```csv
region,q1,q2
EMEA,1,2
APAC,3,4
```
Either form accepts a no-header flag on the info string to suppress
header-row treatment (no row gets bolded; all rows are body):
```csv-file no-header
data/raw.csv
```
CSV-derived tables share the same Table N counter as native markdown
tables, accept the same preceding-Table: caption, and use the
Table Grid style. The delimiter is auto-detected via csv.Sniffer
(falls back to comma); encoding is UTF-8.
Embedding a pandas DataFrame
Pass a DataFrame in the context and pipe it through the built-in
to_csv Jinja2 filter inside a csv fence:
Table: Quarterly figures.
```csv
{{ df | to_csv }}
```
import pandas as pd
df = pd.DataFrame(
{"region": ["EMEA", "APAC"], "q1": [1, 3], "q2": [2, 4]}
)
convert_markdown_text(markdown_text, "out.docx", context={"df": df})
The filter calls value.to_csv(index=False) and strips the trailing
newline. Captions, the shared Table N counter, and the no-header
flag all work the same as for any csv fence.
The filter is duck-typed on .to_csv() — pandas is not a
dependency of md-reports. Any object with a compatible .to_csv()
method works (your script provides it). Pass any kwargs supported by
the underlying method, e.g.:
```csv
{{ df | to_csv(sep=';', na_rep='—', index=True) }}
```
Math
LaTeX math expressions written between dollar delimiters render as native Word equations — the same OMML the Word equation editor produces, so they open as editable equations rather than text or images.
The mass-energy relation is $E = mc^2$.
$$\int_0^1 x^2 \, dx = \tfrac{1}{3}$$
$…$— inline math, placed inside the surrounding paragraph.$$…$$— display math, emitted as its own paragraph.
Whitespace-adjacent dollars ($ 5 and $ 10) are intentionally not
treated as math, so prose containing currency stays untouched.
Display-math paragraphs use a paragraph style named Math equation.
The renderer reuses that style if your template already defines it
(so you can pin alignment, spacing-before/after, indent, etc. there);
otherwise a Math equation style based on Normal is auto-created in
the output document.
LaTeX is converted via math2docx (LaTeX → MathML → OMML). If a given
expression fails to convert (unsupported macro, malformed syntax), the
renderer warns and falls back to the original $…$ source as plain
text. Under strict_mode=True it raises RenderError.
Jinja2 context
Pass a context dict to inject script-side values into the markdown
before parsing. Substitution runs once on the raw markdown text, so
values flow into every textual position — body, headings, table cells,
image paths, CSV file paths, inline CSV data, captions:
convert_markdown_text(
"# {{ title | upper }}\n\nGrowth: **{{ pct }}%**",
"out.docx",
context={"title": "q1 results", "pct": 14.5},
)
The full Jinja2 syntax is available — variables, filters, conditionals, loops:
# {{ report_title }}
{% for finding in findings %}
- {{ finding }}
{% endfor %}
{% if show_appendix %}
## Appendix
See [details]({{ appendix_url }}).
{% endif %}
Supported value types include str, int, float, bool, None,
list/tuple of those, and dict (for attribute access via
{{ user.name }}).
Missing-variable behavior:
- Default mode: a simple
{{ name }}whose key is missing renders as the literal{{ name }}and emits a warning — visible breadcrumb, no silent data loss. More complex Jinja2 errors (syntax errors, iteration over an undefined sequence, etc.) cause the markdown to be left unchanged with a warning. strict_mode=True: any undefined variable or template error raisesValidationError.
MarkdownConverter accepts a default_context at construction
time and per-call context= overrides that merge over it (call-site
keys win).
Keeping the rendered markdown. render_markdown_template runs the
same substitution step on its own and returns the text, using the same
to_csv filter and the same strict_mode/sandboxed_context
handling. Save its result and convert that file. You get a
preview-friendly .md that matches the .docx exactly:
from md_reports import render_markdown_template, convert_markdown_file
built = Path("build/report.md")
built.write_text(
render_markdown_template(source, context, options=opts),
encoding="utf-8",
)
convert_markdown_file(built, "build/report.docx", options=opts)
Organising reports in a project
A recommended layout for keeping reports inside a project repo. It is a convention, not something the library enforces:
reports/
_shared/ # optional: house template.docx, shared helpers
<slug>/ # one folder per report
report.md # source: prose + Jinja2 placeholders
build.py # single entry point: data -> figures -> md -> docx
scripts/ # optional helper modules
data/ # input data (read-only)
assets/ # optional hand-made images
build/ # generated and gitignored: report.md, report.docx,
# figures/, and assets/ copied from ../assets
Everything outside build/ is source. build.py renders report.md
into build/report.md with render_markdown_template, then converts
that file to build/report.docx. Write image paths in the source
relative to build/ (figures/x.png), so the built folder is
self-contained and previews correctly. Rebuild with
uv run python reports/<slug>/build.py.
A working example is in
examples/reports/demo-report/.
Options
from md_reports import ConversionOptions
ConversionOptions(
strict_mode=False, # raise instead of warn on issues
figure_caption_prefix="Figure",
table_caption_prefix="Table",
project_root=None, # root for resolving relative paths
# to images and CSV files
sandboxed_context=False, # sandbox Jinja2 (see Security model)
confine_assets=False, # keep asset paths under project_root
caption_chapter_level=None, # 1-6: number captions per chapter
caption_chapter_separator="-", # Figure 2-3
)
Invalid values (e.g. caption_chapter_level=7) raise
ValidationError when the options are created.
Templates
If template_path is omitted on DocxRenderer (or you don't pass a
renderer at all), a packaged default DOCX template is used. To
inspect or copy the default:
from md_reports import get_default_template_path
print(get_default_template_path())
The template should provide these styles (fallbacks apply when missing):
Normal,Heading 1…Heading 6List Bullet,List Number(and their2/3variants for nesting)Quote,CaptionTable GridCode(optional; falls back to monospace runs inNormal)Math equation(optional; auto-created based onNormalif missing — applied to display-math paragraphs)
With caption_chapter_level set, Heading 1 up to the chapter level
must exist (otherwise TemplateError), and heading list numbering is
added to the output if the template has none. Headings already in the
template body at or above the chapter level are numbered too and count
as chapters (with a warning).
Front matter
Whatever already lives in the template (cover page, headers/footers, title block, table of contents) is preserved — markdown content is appended after the existing body.
Document properties
Set DOCX core properties (the fields shown under File > Info in
Word) via properties=:
convert_markdown_text(
md,
"report.docx",
properties={
"title": "Q4 Report",
"author": "Jane Doe",
"subject": "Quarterly review",
"tags": "revenue, headcount",
"comments": "Reference: REP-2026-Q4",
"category": "Finance",
},
)
To display these in the rendered document, edit the template and
insert the matching field via Insert > Quick Parts > Field… →
Title / Author / Subject / Keywords / Comments / Category.
You can place these in the body, header, or footer. Word recomputes
fields on F9 / print, same as SEQ and REF.
MarkdownConverter also accepts default_properties=, merged with
per-call properties= (call-site keys win).
Accepted keys (case-insensitive) and the core property they target:
| Key (and aliases) | Core property |
|---|---|
title |
title |
author, creator |
author |
subject |
subject |
keywords, tags |
keywords |
comments, description |
comments |
category, categories |
category |
content_status |
content_status |
identifier |
identifier |
language |
language |
version |
version |
last_modified_by |
last_modified_by |
Unknown keys warn (or raise under strict_mode). Datetime properties
(created, modified, last_printed, revision) are deliberately
not exposed.
Company lives in DOCX extended properties (docProps/app.xml),
not core properties, and is not currently writable via this API.
Arbitrary user-defined properties (docProps/custom.xml) are likewise
not yet supported — use subject/keywords/comments as a host for
reference strings or project codes.
Limitations (v1)
- No CLI.
- Remote (
http(s)://) image fetching is not supported — use local files. - Cell merges (
rowspan/colspan) and nested tables are not supported. - CSV embedding has no per-fence delimiter/encoding overrides yet
(UTF-8 +
csv.Snifferonly). SEQfield numbers display correctly in Word once fields update (typically on print or pressingF9); the file is written with a pre-computed display value so first-open looks right too.- No footnotes, definition lists, or task lists.
- Math delimiters are dollar-only (
$…$,$$…$$); LaTeX\(…\)and\[…\]forms are not recognised.
Errors
All exceptions inherit from MdAstDocxError. Specific types:
TemplateError— template missing/unreadableParseError— markdown could not be parsedRenderError— DOCX rendering failedValidationError— bad input arguments
Security model
By default, md-reports treats the markdown source as code-equivalent
— same trust as the script that calls the library. Two consequences
follow that you should know about:
- Jinja2 substitution runs in a non-sandboxed environment. Any
{{ ... }}expression in the markdown can reach into context values' attributes (e.g.{{ obj.__class__... }}). Useful for things like{{ df | to_csv }}, dangerous if the markdown is untrusted. - Asset paths are not confined. Image and CSV references
(
,csv-fileblocks) accept absolute paths and..traversals. The library will read whatever the process can read and embed it into the output.
This is fine for the typical use case (developer-authored markdown, script-supplied context). If you ever pass user-controlled markdown into the library — e.g. a CMS, a comment field, or a user-uploaded file — turn on the two hardening flags:
from md_reports import ConversionOptions, convert_markdown_text
convert_markdown_text(
untrusted_markdown,
"out.docx",
context={"title": "Report"},
options=ConversionOptions(
sandboxed_context=True, # use Jinja2's SandboxedEnvironment
confine_assets=True, # reject paths outside project_root
project_root="/srv/uploads/work_dir",
),
)
sandboxed_context=True swaps the Jinja2 environment for
jinja2.sandbox.SandboxedEnvironment, blocking attribute and
built-in access in template expressions. Note this can break filters
that rely on duck-typed attribute access (the built-in to_csv
filter still works because it uses hasattr/getattr, not
expression-level attribute access). Verify your templates against the
sandboxed environment before rolling it out.
confine_assets=True enforces that every resolved image and CSV path
lies under the asset base — project_root if set, otherwise the
markdown file's directory. Absolute paths and .. traversals that
escape the base are rejected (warned, or raised under strict_mode).
Also note:
- Templates (
template_path=) are loaded bypython-docx/lxmland are otherwise opaque to md-reports. Treat templates as trusted: don't load templates from untrusted sources without reviewing them first. - Hyperlink schemes are limited to
http://,https://, andmailto:; other schemes (includingjavascript:,file:,data:) fall back to plain text. - Remote image fetching is not supported;
http(s)://image paths are explicitly rejected.
Development
uv sync --extra dev
uv run pytest
uv run ruff check src tests
uv run ruff format src tests
Metadata
Release files for md-reports 0.3.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| md_reports-0.3.0.tar.gz | 70.9 kB | Without provenance | Details for md_reports-0.3.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| md_reports-0.3.0-py3-none-any.whl | Python 3 | none | any | Details for md_reports-0.3.0-py3-none-any.whl |
Total release size: 146.1 kB
Release files / md_reports-0.3.0.tar.gz
| Download URL | md_reports-0.3.0.tar.gz |
|---|---|
| Size | 70.9 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
6877e354d18516c76336dc6d492dd8bc829e89b97cc3569f223cd60d31d6db3b
|
|
BLAKE2b-256 checksum How to use checksums |
d1ba2780bb2566913cf8a81bc255081bb6ab5706bd5c6794105f49cada2fa57d
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.12.24 {"installer":{"name":"uv","version":"0.12.24","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":null,"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}
|
Release files / md_reports-0.3.0-py3-none-any.whl
| Download URL | md_reports-0.3.0-py3-none-any.whl |
|---|---|
| Size | 75.2 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
3334b8f02639dc71710ad8ed6d560a8c9805d4b822e63c39898a27508377710f
|
|
BLAKE2b-256 checksum How to use checksums |
2dc745f359f14324348e6afdaaeb66286a273457f60aa9c11bf9c1138ec64eac
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.12.24 {"installer":{"name":"uv","version":"0.12.24","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":null,"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}
|
Security for md-reports 0.3.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.