agentleFS
fabioc-alohafabioc-aloha/Alex_ACT_ONE/skills/md-to-word/SKILL.md

md-to-word

Skill0 starsChanged 9 days agoMITView on GitHub

Convert Markdown with Mermaid diagrams and SVG illustrations to professional Word documents. Use when the user asks to convert to Word, make a docx, or export markdown as a .docx file.

  • Installs packages

4 other projects use a version of this, 2 of them edited.

Adopted by

Most recently taken up by

The file

We split this skill into the rules it gives an agent

11 rules. 7 are common, 2 are distinctive, and 2 are very specific to this project.

  • 7

    Common

    Most of the 3 edited versions we read keep these.

  • 2

    Distinctive

    This author's own choices. Worth a look.

  • 2

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    Convert to Word: Run md-to-word.cjs — produces a complete, styled document

    line 39
  2. Common:

    Optional polish: Add page breaks, headers/footers, custom branding

    line 40
  3. Common:

    All Mermaid diagram types are supported:

    line 66
  4. Common:

    Use viewBox for scalable graphics

    line 205
  5. Common:

    Keep file size under 500KB for fast conversion

    line 207
  6. Common:

    Avoid external references (they won't resolve)

    line 208
  7. Very specific:

    When a Mermaid block has no classDef, no %%{init}%% directive, and no explicit theme variables, the converter injects a default pastel …

    line 243
  8. Distinctive:

    All tables receive professional OOXML styling (tightened in v5.5.0 for denser, more reference-document-style tables):

    line 288
  9. Common:

    All headings: keepNext + keepLines (no orphans)

    line 314
  10. Common:

    Keep together: Won't split across pages

    line 321
  11. Distinctive:

    Not earning tokens if the user must manually fix the same structural or styling issues on every conversion

    line 498

“Common” is measured: kept by at least 6 in 10 of the 3 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Md To Word

One command to professional Word documents — diagrams, tables, and formatting done right on first attempt.

Convert any Markdown document into polished Word (.docx) files ready for stakeholders, executives, and external audiences. Supports all standard Markdown formatting, Mermaid diagrams (auto-converted to PNG), and SVG illustrations (auto-embedded).

Why Use This?

Without This SkillWith This Skill
Mermaid diagrams missing or brokenAuto-rendered to high-res PNG, optimally sized
SVG images not displayingAuto-converted to PNG with proper dimensions
Tables plain and unprofessionalMicrosoft-branded headers, borders, zebra striping
Tables split mid-row across pagesSmart pagination keeps rows intact
Images overflow page boundaries90% page coverage constraint ensures fit
Bullet lists merge into paragraphsPreprocessor fixes spacing automatically
Code blocks lose formattingConsolas font, gray background, proper borders
Links plain textBlue underlined hyperlinks
Headings inconsistentBranded colors, proper hierarchy

Document Publishing Workflow

Markdown (.md)  →  md-to-word.cjs  →  Word (.docx)  →  Final PDF
     ↓                   ↓                ↓               ↓
  Source            Automation      Manual polish     Distribution
  (your docs)      (this skill)    (page breaks,     (File > Save As)
                                    headers/footers)
  1. Convert to Word: Run md-to-word.cjs — produces a complete, styled document
  2. Optional polish: Add page breaks, headers/footers, custom branding
  3. Export PDF: Word's File > Save As > PDF gives best fidelity

Supported Markdown Formatting

FeatureSupportNotes
Headings (H1-H6)✅ FullBranded colors, proper spacing
Bold/Italic/Strikethrough✅ Full**bold**, *italic*, ~~strike~~
Bullet lists✅ FullNested supported
Numbered lists✅ FullAuto-numbered
Task lists✅ Full- [ ] / - [x] converted
Tables✅ FullProfessional styling
Code blocks✅ FullMonospace styling preserved
Inline code✅ FullMonospace with background
Links✅ FullBlue underlined
Images (PNG/JPG)✅ FullCentered, auto-sized
SVG images✅ Auto-convertRendered to PNG
Mermaid diagrams✅ Auto-convertRendered to PNG
Blockquotes✅ FullGray left border
Horizontal rules✅ FullLight gray line
Footnotes✅ PandocVia pandoc extension
YAML frontmatter✅ Strip--strip-frontmatter option

Mermaid Diagram Support

All Mermaid diagram types are supported:

Diagram TypeDetectionSizing Strategy
Flowchart LRflowchart lrWidth priority (6.5")
Flowchart TBflowchart tbHeight priority (3.6")
SequencesequenceDiagramWidth priority
GanttganttWidth priority (wide)
ClassclassDiagramAuto
ERerDiagramAuto
StatestateDiagramAuto
PiepieSmaller width
MindmapmindmapWidth priority
TimelinetimelineWidth priority

Diagrams are rendered at 4x scale (4800px width) for crisp printing, then sized to fit within page bounds.

Rendered PNGs are checked for chunk structure/checksums, valid dimensions, complete compressed raster data, and row filters before replacing an existing diagram. Decompressed raster data, including scanline filter bytes, is limited to 256 MiB before inflation. Split an oversized diagram or pre-render it at a smaller resolution rather than bypassing validation.

The Word document and newly generated images are staged until rendering, Pandoc, and document post-processing all succeed. A failure before publication preserves the complete prior output set, even when an earlier diagram succeeded. Handled publication errors roll back replaced files; failed rollback reports the retained recovery copies. This does not guarantee atomicity across process crashes or power loss.


Quick Start

One-Command Conversion

# From your project root
node skills/md-to-word/scripts/md-to-word.cjs docs/spec.md

# With custom output name
node skills/md-to-word/scripts/md-to-word.cjs README.md output.docx

# Keep intermediate files for debugging
node skills/md-to-word/scripts/md-to-word.cjs docs/plan.md --keep-temp

What It Does

  1. Preprocesses Markdown — fixes bullet lists, checkbox syntax, spacing
  2. Converts Mermaid to PNG — renders diagrams with white backgrounds
  3. Calculates optimal sizing — reads actual PNG dimensions, fits 90% of page
  4. Converts SVG to PNG — handles banner images
  5. Generates Word via pandoc — clean markdown-to-docx conversion
  6. Formats tables — Microsoft blue headers, borders, alternating rows
  7. Centers images — all diagrams centered on page
  8. Styles headings — consistent colors and spacing

Installation

Prerequisites

ToolPurposeRequired?
Node.js 24+Script runtimeYes
pandocMarkdown to WordYes
mermaid-cliMermaid diagrams to PNGOnly for diagrams
jszipOOXML post-processing (table formatting, image centering)No — degrades
svgexportSVG to PNGNo

To check what is present and install what is missing:

/alex-act-one setup-dependencies

That command owns the install instructions for every platform, so they exist in one place and cannot drift from what the scripts actually look for. Running a conversion without a required tool also prints the exact command for your platform at the moment you need it.


Options

OptionDefaultDescription
--tocoffGenerate Table of Contents. A [toc] marker in the source is stripped but does not auto-enable TOC (since v5.5.0). When the marker is found without --toc, a warning is logged so the heir can either pass --toc explicitly or remove the marker.
--coveroffGenerate cover page from H1 + date
--style PRESETprofessionalStyle preset (see below)
--page-size SIZEletterPage size: letter, a4, 6x9
--reference-doc PATH—Custom Word template (.dotx)
--images-dir DIRimagesDirectory for generated PNG files
--embed-imagesoffEmbed local images as base64
--strip-frontmatteronRemove YAML frontmatter
--no-format-tablesoffSkip table styling (faster)
--keep-tempoffKeep temporary files for debugging
--watchoffAuto-rebuild on source change
--recursiveoffProcess all .md files in directory
--dry-runoffValidate only, no output
--debugoffSave preprocessed markdown

Style Presets

PresetBody FontHeading StyleUse Case
professionalAptos 11ptAptos Display, navy and teal hierarchyBusiness documents, specs, reports
academicTimes New Roman 12ptBlack, double-spacedDissertations, papers, theses
courseCalibri 11ptVirginia Tech burgundyCourse materials, syllabi
creativeGeorgia 11ptSlate blueBlog posts, narratives
# Academic paper with TOC
node md-to-word.cjs thesis.md --style academic --toc

# Professional report with cover
node md-to-word.cjs quarterly-report.md --style professional --cover --toc

SVG Image Handling

SVG files are automatically detected and converted to PNG for Word compatibility:

<!-- This SVG reference in your Markdown... -->
![Architecture](<your-diagram>.svg)

<!-- ...becomes this embedded PNG in Word -->
![Architecture](<your-diagram>.png){width=5.8in}

Requirements: svgexport — run /alex-act-one setup-dependencies to check and install

Best practices for SVG sources:

  • Use viewBox for scalable graphics
  • Embed fonts or use web-safe font stack
  • Keep file size under 500KB for fast conversion
  • Avoid external references (they won't resolve)

Image Sizing Algorithm

The script automatically fits images to page bounds. The constraints are codified in md-to-word.cjs:

Page: 8.5" × 11" (Letter)
Margins: 1" each side
Usable area: 6.5" × 9.0"
MAX_IMAGE_WIDTH_RATIO  = 0.90   →  max width  ≈ 5.85"
MAX_IMAGE_HEIGHT_RATIO = 0.60   →  max height ≈ 5.40"

These ratios apply width-priority for landscape/wide diagrams (LR flowcharts, gantts, sequence diagrams) and height-priority for portrait/tall diagrams (TB/TD flowcharts with multiple subgraphs). The algorithm picks the more restrictive constraint so the image fits in both dimensions.

Algorithm Steps

  1. Read PNG dimensions from file header (pure Node.js, no dependencies)
  2. Calculate scale factors for width and height constraints
  3. Apply most restrictive — ensures fit in both dimensions
  4. Specify constraining dimension — pandoc preserves aspect ratio

Mermaid Palette and Fidelity

When a Mermaid block has no classDef, no %%{init}%% directive, and no explicit theme variables, the converter injects a default pastel palette (GitHub-style soft colors with dark text) before rendering. This gives WYSIWYG fidelity to authors who don't styled-by-design every diagram.

Why per-diagram-type injection matters

Diagram typeHonors classDef?Color path
flowchart / graphYesclassDef (preferred) or injected init
classDiagramPartialclassDef or injected init
sequenceDiagramNothemeVariables only (e.g. actorBkg, noteBkgColor)
stateDiagram-v2NothemeVariables only (primaryColor, mainBkg, labelBoxBkgColor)
erDiagramNothemeVariables only

Without diagram-type-aware injection, sequence and state diagrams would render as flat neutral nodes regardless of any classDef the author wrote.

Behavior

  • flowchart / graph / classDiagram with classDef → respected, no injection (author wins)
  • flowchart / graph without classDef → palette injected + lint nudge
  • sequenceDiagram / stateDiagram-v2 without %%{init}%% or explicit actorBkg / primaryColor → palette injected (only path to colors)
  • Any block with %%{init}%% already present → respected, no injection

Opting out

Pass --no-default-palette to disable injection. Diagrams without classDef or explicit theme will then render with mermaid's default neutral theme, and a warning is emitted per affected diagram.

Lint warnings

During preprocessing the converter emits 💡 nudges for unstyled flowcharts ("inject default pastel palette") and ⚠️ warnings when --no-default-palette is set on diagrams that would have rendered flat.


Table Formatting

All tables receive professional OOXML styling (tightened in v5.5.0 for denser, more reference-document-style tables):

ElementStyle
Header rowMicrosoft blue (#0078D4), white text, bold 9pt
Even data rowsLight gray (#F0F0F0)
Odd data rowsWhite (#FFFFFF)
Data cell font8.5pt black
BordersGray outer (#666666), light inner (#AAAAAA)
Cell padding1pt top/bottom, 3pt left/right
PaginationcantSplit + keepWithNext (no orphan headers)
Repeat headersHeader row repeats on each page for long tables

Professional Features

Page Numbers

Centered page numbers in the footer, gray text (9pt).

Heading Hierarchy

  • H1: Aptos Display 24pt, navy, bold, 360/120 twip spacing
  • H2: Aptos Display 16pt, teal, bold, 280/120 twip spacing
  • H3: Aptos Display 14pt, blue, bold, 240/80 twip spacing
  • All headings: keepNext + keepLines (no orphans)

Code Blocks

  • Font: Consolas 9pt
  • Background: Light gray (#F5F5F5)
  • Border: Left accent bar (#CCCCCC)
  • Keep together: Won't split across pages

Hyperlinks

  • Color: Microsoft blue (#0563C1)
  • Style: Single underline
  • Applied to both inline links and reference links

Captions

Paragraphs starting with "Table N" or "Figure N":

  • Centered, italic, 9pt gray
  • keepNext binding to following content

Troubleshooting

IssueCauseFix
"mmdc not found"mermaid-cli not installedRun /alex-act-one setup-dependencies
"pandoc not found"pandoc not in PATHRun /alex-act-one setup-dependencies, then restart the terminal
"svgexport not found"svgexport not installedRun /alex-act-one setup-dependencies
Tables not styledjszip not availableUse the unified setup helper or select the matching private runtime with ALEX_ACT_ONE_RUNTIME_ROOT
Diagrams too smallOutdated scriptUpdate to v5.3.0+
Images overflowComplex diagramUse --debug and check PNG dimensions
SVG not convertingMissing svgexportInstall or use PNG source
Document corruptIncomplete writeCheck disk space, re-run

Debug Mode

node md-to-word.cjs doc.md --debug --keep-temp
# Check _debug_combined.md for preprocessed content
# Check images/ folder for generated PNGs

macOS Fallback (No Pandoc)

macOS ships textutil which can convert HTML to DOCX natively:

# Convert markdown to HTML first, then HTML to DOCX
npx marked document.md -o document.html
textutil -convert docx document.html -output document.docx
FeaturePandoc (primary)textutil (fallback)
Table stylingFull (via jszip post-processing)Basic
Mermaid diagramsSupported (pre-rendered PNG)Must be pre-rendered
Heading stylesMapped to Word stylesBasic HTML mapping
Cross-referencesSupportedNot supported
Installbrew install pandocBuilt-in (macOS only)

Limitations: textutil needs HTML input (not raw Markdown), produces simpler formatting, and doesn't support the table styling or image sizing that md-to-word.cjs provides. Use only when Pandoc is unavailable and a quick conversion is needed.


Batch Processing

Convert a Folder

# Windows PowerShell
Get-ChildItem docs/*.md | ForEach-Object {
    node skills/md-to-word/scripts/md-to-word.cjs $_.FullName --style professional
}
# macOS/Linux
for f in docs/*.md; do
    node skills/md-to-word/scripts/md-to-word.cjs "$f" --style professional
done

Recursive Directory

# All .md files in docs/ and subdirectories
node skills/md-to-word/scripts/md-to-word.cjs docs --recursive --style professional

Watch Mode

# Auto-rebuild when source changes
node skills/md-to-word/scripts/md-to-word.cjs spec.md --watch

Integration Examples

GitHub Actions CI/CD

Pandoc must already be provisioned on the runner. Resolve optional npm tool versions from this checkout's shared registry rather than copying old pins:

<!-- dependency-pin-example:start -->
const d = require('./scripts/shared/dependencies.cjs');
console.log(JSON.stringify(['mmdc', 'svgexport'].map(key => d.specOf(d.TOOLS[key]))));
<!-- dependency-pin-example:end -->
# Generate Word docs as build artifacts
- name: Generate Word Documents
  shell: pwsh
  run: |
    $specs = node -e "const d = require('./scripts/shared/dependencies.cjs'); console.log(JSON.stringify(['mmdc', 'svgexport'].map(key => d.specOf(d.TOOLS[key]))));" | ConvertFrom-Json
    if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
    npm install --global @specs
    if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
    node skills/md-to-word/scripts/md-to-word.cjs docs/spec.md --toc --cover

- name: Upload artifacts
  uses: actions/upload-artifact@v4
  with:
    name: word-documents
    path: docs/*.docx

npm Script

{
  "scripts": {
    "docs:word": "node skills/md-to-word/scripts/md-to-word.cjs docs/README.md --style professional --toc"
  }
}

For Other Projects

  1. Copy skills/md-to-word/scripts/md-to-word.cjs to the same relative path in the target project.
  2. Copy the complete scripts/shared/ directory to the same relative path in the target project. Keep its helpers together, including process-command.cjs and runtime-status.cjs, so unconditional and transitive imports resolve.
  3. Install prerequisites: Pandoc is required; jszip, Mermaid CLI, and svgexport are optional format helpers. The copied tool-runner still prints the install command for any missing tool.
  4. Run: node skills/md-to-word/scripts/md-to-word.cjs your-doc.md.

Version History and Acceptance Criteria

Full version history and the conversion acceptance decision table moved to references/version-history-and-acceptance.md to keep this file under the Agent Skills recommended body length.


Related Skills

SkillRelationship
markdown-mermaidMermaid syntax and ATACCU compliance
lint-clean-markdownPre-flight the source — pass clean Markdown in
markdown-sanitization-chainSanitize user-supplied Markdown before conversion
markdown-mermaid § Mode FragilityWhy we default to flowchart mode
md-to-htmlHTML output with same preprocessing

Falsifiability

  • This skill is wrong if .docx files produced per its guidance fail to open or lose formatting on round-trip (Word → save → reopen)
  • The reference-doc approach is stale if Pandoc changes how --reference-doc applies styles in a major version
  • Not earning tokens if the user must manually fix the same structural or styling issues on every conversion

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.