Back to skills
SkillHub ClubWrite Technical DocsFull StackTech Writer

md2docx

Convert Markdown to Word (DOCX) documents. Use when user wants to export, convert, or create Word documents from Markdown content.

Packaged view

This page reorganizes the original catalog entry around fit, installability, and workflow context first. The original raw source lives below.

Stars
117
Hot score
95
Updated
March 20, 2026
Overall rating
C2.8
Composite score
2.8
Best-practice grade
A85.2

Install command

npx @skill-hub/cli install yorick-ryu-deep-share-md2docx

Repository

Yorick-Ryu/deep-share

Skill path: .claude/skills/md2docx

Convert Markdown to Word (DOCX) documents. Use when user wants to export, convert, or create Word documents from Markdown content.

Open repository

Best for

Primary workflow: Write Technical Docs.

Technical facets: Full Stack, Tech Writer.

Target audience: everyone.

License: Unknown.

Original source

Catalog source: SkillHub Club.

Repository owner: Yorick-Ryu.

This is still a mirrored public skill entry. Review the repository before installing into production workflows.

What it helps with

  • Install md2docx into Claude Code, Codex CLI, Gemini CLI, or OpenCode workflows
  • Review https://github.com/Yorick-Ryu/deep-share before adding md2docx to shared team environments
  • Use md2docx for development workflows

Works across

Claude CodeCodex CLIGemini CLIOpenCode

Favorites: 0.

Sub-skills: 0.

Aggregator: No.

Original source / Raw SKILL.md

---
name: md2docx
description: Convert Markdown to Word (DOCX) documents. Use when user wants to export, convert, or create Word documents from Markdown content.
api_key: ""
---

# md2docx - Markdown to Word Converter

Convert Markdown text to professionally formatted Word (DOCX) documents.

## Quick Start

**Choose the right mode based on your environment**:

```bash
# URL mode: Returns download URL (for cloud/remote environments)
python scripts/convert.py input.md --url

# File mode: Saves file directly (for local environments)
python scripts/convert.py input.md --file
```

## Choosing the Right Mode

| Scenario | Mode | Command |
|----------|------|---------|
| Skill runs in cloud, user needs to download | `--url` | `python scripts/convert.py input.md --url` |
| Skill runs locally, user wants file saved | `--file` | `python scripts/convert.py input.md --file` |
| Remote execution (MCP, API, cloud agent) | `--url` | Returns URL for user to download |
| Local execution (user's machine) | `--file` | Saves .docx directly to disk |

**Decision Rule**:
- **Use `--url`** when the skill runs in a different environment than the user (cloud, remote server, MCP server)
- **Use `--file`** when the skill runs on the same machine where the user wants the output file

## How It Works

1. **Prepare Markdown**: Ensure content is in standard Markdown format
2. **Run Script**: Execute `scripts/convert.py` with appropriate mode
3. **Get Result**: 
   - URL mode: Receive download URL
   - File mode: File saved to specified location

## API Details

**Endpoints**:
- URL mode: `https://api.deepshare.app/convert-text-to-url` → Returns `{"url": "..."}`
- File mode: `https://api.deepshare.app/convert-text` → Returns DOCX file directly

**Authentication**: Include header `X-API-Key: {api_key}`

### API Key Configuration

You can configure the API key in three ways:

1. **Environment Variable** (Highest Priority)
   ```bash
   export DEEP_SHARE_API_KEY="your_api_key_here"
   ```

2. **Skill Variable** (Medium Priority)
   Edit the `api_key` field in the YAML frontmatter of this Skill file:
   ```yaml
   ---
   name: md2docx
   api_key: "your_api_key_here"
   ---
   ```

3. **Trial Key** (Fallback): `f4e8fe6f-e39e-486f-b7e7-e037d2ec216f`

**Priority Order**:
1. Environment variable `DEEP_SHARE_API_KEY` (if set)
2. Skill's `api_key` variable (if not empty)
3. Trial key (limited quota)

⚠️ **Trial Mode**: Limited quota. For stable production use, purchase at: https://ds.rick216.cn/purchase

## Request Format

```json
{
  "content": "markdown text here",
  "filename": "output",
  "template_name": "templates",
  "language": "zh",
  "hard_line_breaks": false,
  "remove_hr": false
}
```

## Parameters

| Parameter | Default | Description |
|-----------|---------|-------------|
| `content` | required | Markdown text to convert |
| `filename` | `"output"` | Output filename (without .docx) |
| `template_name` | `"templates"` | Template: `templates`, `论文`, `article`, `thesis`, etc. |
| `language` | `"zh"` | Template language: `zh` or `en` |
| `hard_line_breaks` | `false` | Preserve single line breaks |
| `remove_hr` | `false` | Remove horizontal rules |

## Common Templates

**Chinese** (`language: "zh"`):
- `templates` - General purpose
- `论文` - Academic paper
- `论文-首行不缩进` - Paper without indent
- `论文-标题加粗` - Paper with bold headings

**English** (`language: "en"`):
- `templates` - General purpose
- `article` - Article/report style
- `thesis` - Academic thesis

## Conversion Script Usage

### Command Line Options

```bash
python scripts/convert.py <input.md> [options]

Options:
  --url              Return download URL (default if no mode specified)
  --file             Save file directly to disk
  --template, -t     Template name (default: templates)
  --language, -l     Language: zh or en (default: zh)
  --output, -o       Output directory for file mode
  --api-key, -k      API key (optional)
```

### Examples

```bash
# URL mode (cloud/remote environments)
python scripts/convert.py document.md --url
python scripts/convert.py paper.md --url --template 论文 --language zh

# File mode (local environments)
python scripts/convert.py document.md --file
python scripts/convert.py paper.md --file --output ./docs --template thesis --language en

# With custom API key
python scripts/convert.py doc.md --url --api-key your_key
```

## Validation Before Conversion

Ensure Markdown content:
- Headers use `#` syntax
- Lists use `-` or `1.` syntax
- Code blocks use triple backticks
- Math formulas use `$...$` (inline) or `$$...$$` (block)
- Images use publicly accessible URLs

## Response Handling

### URL Mode Response

**Success** (200 OK):
```json
{
  "url": "https://flies.deepshare.app/mcp/hash/document_xxx.docx"
}
```

### File Mode Response

**Success**: File saved to disk, path printed to stdout

### Error Responses (Both Modes)

- `401 Unauthorized` - Invalid API key
- `403 Forbidden` - Quota exceeded → Purchase at https://ds.rick216.cn/purchase
- `413 Payload Too Large` - Content exceeds 10MB
- `500 Internal Server Error` - Service unavailable, retry

## User Communication

### On Success

Tell user:
1. Conversion completed successfully
2. **URL mode**: Provide the download URL
3. **File mode**: Provide the file path where document was saved
4. Check which API key was used:
   - **If using environment variable or Skill variable**: No reminder needed
   - **If using trial key**: Remind: "⚠️ You're using trial mode (limited quota). For stable production use, get your API key at: https://ds.rick216.cn/purchase"

### On Quota Exceeded

Tell user:
1. Conversion failed: quota exceeded
2. Purchase more credits at: https://ds.rick216.cn/purchase
3. Or use another API key

### On Other Errors

Tell user:
1. What went wrong (based on error message)
2. How to fix it
3. Offer to retry

## Tips

- **API Key Configuration**:
  - **Option 1 (Recommended)**: Set environment variable `DEEP_SHARE_API_KEY`
    ```bash
    export DEEP_SHARE_API_KEY="your_api_key_here"
    ```
  - **Option 2**: Edit `api_key` in this Skill's YAML frontmatter
  - **Option 3**: Use trial key (limited quota)
- **File Size**: Keep Markdown under 10MB
- **Images**: Use `https://` URLs, not local paths
- **Math**: Use LaTeX syntax: `$E=mc^2$` or `$$\int_0^\infty$$`
- **Line Breaks**: Use `hard_line_breaks: true` for addresses, poetry
- **Templates**: Choose based on document type (paper, article, etc.)

## Example Workflows

### Workflow 1: Cloud Environment (URL Mode)

**User asks**: "Convert this to Word" (skill running in cloud)

1. Save the Markdown content to a temporary file (e.g., `temp.md`)

2. Run the conversion script with URL mode:
   ```bash
   python scripts/convert.py temp.md --url
   ```

3. The script will:
   - Select API key by priority (env → skill → trial)
   - Call the conversion API
   - Return download URL

4. Provide the download URL to user

5. Clean up temporary file

### Workflow 2: Local Environment (File Mode)

**User asks**: "Convert my notes.md to Word" (skill running locally)

1. Run the conversion script with file mode:
   ```bash
   python scripts/convert.py notes.md --file --output ./output
   ```

2. The script will:
   - Select API key by priority (env → skill → trial)
   - Call the conversion API
   - Save the DOCX file directly

3. Tell user where the file was saved

4. No cleanup needed - file is the output


---

## Referenced Files

> The following files are referenced in this skill and included for context.

### scripts/convert.py

```python
#!/usr/bin/env python3
"""
Simple md2docx conversion script.
Converts Markdown to DOCX via API.

Supports two modes:
- URL mode (--url): Returns download URL, for cloud/remote environments
- File mode (--file): Downloads file directly, for local environments
"""

import os
import sys
import argparse
import requests

# API Configuration
API_BASE = "https://api.deepshare.app"
API_URL_TO_URL = f"{API_BASE}/convert-text-to-url"  # Returns URL
API_URL_TO_FILE = f"{API_BASE}/convert-text"        # Returns file directly
TRIAL_KEY = "f4e8fe6f-e39e-486f-b7e7-e037d2ec216f"
PURCHASE_URL = "https://ds.rick216.cn/purchase"


def get_api_key(explicit_key=None, skill_api_key=None):
    """Get API key by priority: explicit > env > skill > trial."""
    if explicit_key:
        return explicit_key, False
    
    env_key = os.environ.get('DEEP_SHARE_API_KEY')
    if env_key:
        return env_key, False
    
    if skill_api_key:
        return skill_api_key, False
    
    return TRIAL_KEY, True


def handle_error_response(response):
    """Handle error responses from API."""
    if response.status_code == 403:
        print("\n✗ Conversion failed: Quota exceeded")
        print(f"\nYour account has run out of credits.")
        print(f"Purchase more at: {PURCHASE_URL}")
        sys.exit(1)
    elif response.status_code == 401:
        print("\n✗ Conversion failed: Invalid API key")
        print(f"\nGet a valid API key at: {PURCHASE_URL}")
        sys.exit(1)
    elif response.status_code == 413:
        print("\n✗ Conversion failed: Content too large")
        print("\nMaximum size is 10MB. Please reduce content size.")
        sys.exit(1)
    else:
        print(f"\n✗ Conversion failed: {response.status_code}")
        try:
            detail = response.json().get("detail", "Unknown error")
            print(f"Error: {detail}")
        except:
            print(f"Error: {response.text}")
        sys.exit(1)


def convert_to_url(content, filename="output", template="templates", language="zh", 
                   api_key=None, skill_api_key=None):
    """
    Convert Markdown to DOCX and return download URL.
    Use this when:
    - Skill runs in cloud environment
    - User needs to access file from a different machine
    """
    key, using_trial = get_api_key(api_key, skill_api_key)
    
    headers = {
        "Content-Type": "application/json",
        "X-API-Key": key
    }
    
    payload = {
        "content": content,
        "filename": filename,
        "template_name": template,
        "language": language
    }
    
    try:
        print("Converting Markdown to DOCX (URL mode)...")
        response = requests.post(API_URL_TO_URL, json=payload, headers=headers, timeout=60)
        
        if response.status_code == 200:
            result = response.json()
            url = result.get("url")
            
            print("\n✓ Conversion successful!")
            print(f"\nDownload URL:\n{url}")
            
            if using_trial:
                print(f"\n⚠️  You're using trial mode (limited quota).")
                print(f"For stable production use, get your API key at: {PURCHASE_URL}")
            
            return {"mode": "url", "url": url, "using_trial": using_trial}
        else:
            handle_error_response(response)
            
    except requests.exceptions.Timeout:
        print("\n✗ Request timeout. Please try again.")
        sys.exit(1)
    except requests.exceptions.RequestException as e:
        print(f"\n✗ Network error: {e}")
        sys.exit(1)
    except Exception as e:
        print(f"\n✗ Unexpected error: {e}")
        sys.exit(1)


def convert_to_file(content, filename="output", template="templates", language="zh",
                    output_dir=None, api_key=None, skill_api_key=None):
    """
    Convert Markdown to DOCX and save file directly.
    Use this when:
    - Skill runs locally
    - User wants to save file in the current environment
    """
    key, using_trial = get_api_key(api_key, skill_api_key)
    
    headers = {
        "Content-Type": "application/json",
        "X-API-Key": key
    }
    
    payload = {
        "content": content,
        "filename": filename,
        "template_name": template,
        "language": language
    }
    
    try:
        print("Converting Markdown to DOCX (file mode)...")
        response = requests.post(API_URL_TO_FILE, json=payload, headers=headers, timeout=60)
        
        if response.status_code == 200:
            # Determine output path
            if output_dir:
                os.makedirs(output_dir, exist_ok=True)
                output_path = os.path.join(output_dir, f"{filename}.docx")
            else:
                output_path = f"{filename}.docx"
            
            # Save file
            with open(output_path, 'wb') as f:
                f.write(response.content)
            
            abs_path = os.path.abspath(output_path)
            print("\n✓ Conversion successful!")
            print(f"\nFile saved to:\n{abs_path}")
            
            if using_trial:
                print(f"\n⚠️  You're using trial mode (limited quota).")
                print(f"For stable production use, get your API key at: {PURCHASE_URL}")
            
            return {"mode": "file", "path": abs_path, "using_trial": using_trial}
        else:
            handle_error_response(response)
            
    except requests.exceptions.Timeout:
        print("\n✗ Request timeout. Please try again.")
        sys.exit(1)
    except requests.exceptions.RequestException as e:
        print(f"\n✗ Network error: {e}")
        sys.exit(1)
    except Exception as e:
        print(f"\n✗ Unexpected error: {e}")
        sys.exit(1)


def main():
    parser = argparse.ArgumentParser(
        description="Convert Markdown to Word (DOCX)",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Examples:
  # Return download URL (for cloud environments)
  python convert.py input.md --url
  
  # Save file directly (for local environments)  
  python convert.py input.md --file
  python convert.py input.md --file --output ./docs
  
  # With template and language
  python convert.py paper.md --file --template 论文 --language zh
  
  # With custom API key
  python convert.py doc.md --url --api-key your_key
"""
    )
    
    parser.add_argument("input", help="Input Markdown file")
    
    # Mode selection (mutually exclusive)
    mode_group = parser.add_mutually_exclusive_group()
    mode_group.add_argument("--url", action="store_true", 
                           help="Return download URL (for cloud/remote access)")
    mode_group.add_argument("--file", action="store_true",
                           help="Save file directly (for local use)")
    
    # Optional parameters
    parser.add_argument("--template", "-t", default="templates",
                       help="Template name (default: templates)")
    parser.add_argument("--language", "-l", default="zh",
                       help="Language: zh or en (default: zh)")
    parser.add_argument("--output", "-o", default=None,
                       help="Output directory for file mode")
    parser.add_argument("--api-key", "-k", default=None,
                       help="API key (optional, uses env/trial if not provided)")
    
    args = parser.parse_args()
    
    # Read input file
    try:
        with open(args.input, 'r', encoding='utf-8') as f:
            content = f.read()
    except FileNotFoundError:
        print(f"Error: File not found: {args.input}")
        sys.exit(1)
    except Exception as e:
        print(f"Error reading file: {e}")
        sys.exit(1)
    
    # Get filename from input
    filename = os.path.splitext(os.path.basename(args.input))[0]
    
    # Get skill_api_key from environment (set by Skill when invoked)
    skill_api_key = os.environ.get('SKILL_API_KEY')
    
    # Determine mode (default to URL if not specified)
    if args.file:
        convert_to_file(
            content=content,
            filename=filename,
            template=args.template,
            language=args.language,
            output_dir=args.output,
            api_key=args.api_key,
            skill_api_key=skill_api_key
        )
    else:
        # Default to URL mode (--url or no flag)
        convert_to_url(
            content=content,
            filename=filename,
            template=args.template,
            language=args.language,
            api_key=args.api_key,
            skill_api_key=skill_api_key
        )


if __name__ == '__main__':
    main()

```

md2docx | SkillHub