🏠 > Examples

☀️ 🌙

Examples

This document provides real-world examples for using mk2html and mk2pdf.

Table of Contents


Basic Examples

Simple README Conversion

mk2html README.md

Documentation with Custom Title

mk2html docs/api.md -o website/api-reference.html --title "API Reference v2.0"

Quick PDF Export

mk2pdf report.md -o quarterly-report.pdf --page-size letter

Mermaid Diagrams

Flowchart

<div class="mermaid">
graph TD
    A[Start] --> B{Is it working?}
    B -->|Yes| C[Great!]
    B -->|No| D[Debug]
    D --> B
    C --> E[End]
</div>

Sequence Diagram

<div class="mermaid">
sequenceDiagram
    participant User
    participant API
    participant Database

    User->>API: Request data
    API->>Database: Query
    Database-->>API: Results
    API-->>User: Response
</div>

Class Diagram

<div class="mermaid">
classDiagram
    class Animal {
        +String name
        +int age
        +makeSound()
    }
    class Dog {
        +String breed
        +bark()
    }
    class Cat {
        +String color
        +meow()
    }
    Animal <|-- Dog
    Animal <|-- Cat
</div>

Gantt Chart

<div class="mermaid">
gantt
    title Project Timeline
    dateFormat  YYYY-MM-DD
    section Planning
    Research           :a1, 2024-01-01, 30d
    Design             :a2, after a1, 20d
    section Development
    Implementation     :a3, after a2, 40d
    Testing            :a4, after a3, 20d
    section Deployment
    Launch             :a5, after a4, 10d
</div>

Pie Chart

<div class="mermaid">
pie title Language Distribution
    "Python" : 45
    "JavaScript" : 30
    "Go" : 15
    "Other" : 10
</div>

State Diagram

<div class="mermaid">
stateDiagram-v2
    [*] --> Idle
    Idle --> Processing : Start
    Processing --> Completed : Success
    Processing --> Failed : Error
    Failed --> Idle : Retry
    Completed --> [*]
</div>

Code Blocks

Python with Syntax Highlighting

```python
from typing import List, Optional

class DataProcessor:
    """Process and transform data."""

    def __init__(self, config: dict):
        self.config = config
        self.results: List[dict] = []

    def process(self, data: List[dict]) -> Optional[List[dict]]:
        """Process the input data."""
        if not data:
            return None

        for item in data:
            result = self._transform(item)
            self.results.append(result)

        return self.results

    def _transform(self, item: dict) -> dict:
        return {k: v.upper() if isinstance(v, str) else v 
                for k, v in item.items()}
```

JavaScript/TypeScript

```typescript
interface User {
  id: number;
  name: string;
  email: string;
}

async function fetchUsers(): Promise<User[]> {
  const response = await fetch('/api/users');
  if (!response.ok) {
    throw new Error(`HTTP error! status: ${response.status}`);
  }
  return response.json();
}

// Usage
fetchUsers()
  .then(users => console.log(users))
  .catch(error => console.error('Failed:', error));
```

Shell Commands

```bash
#!/bin/bash

# Convert all markdown files to HTML
for file in docs/*.md; do
    output="${file%.md}.html"
    echo "Converting $file to $output"
    mk2html "$file" -o "$output" --offline
done

echo "Done! Converted $(ls docs/*.html | wc -l) files."
```

SQL

```sql
-- Get top customers by order value
SELECT 
    c.customer_name,
    COUNT(o.order_id) as total_orders,
    SUM(o.total_amount) as lifetime_value
FROM customers c
JOIN orders o ON c.customer_id = o.customer_id
WHERE o.order_date >= DATE_SUB(CURDATE(), INTERVAL 1 YEAR)
GROUP BY c.customer_id, c.customer_name
HAVING lifetime_value > 10000
ORDER BY lifetime_value DESC
LIMIT 10;
```

Tables

Simple Table

| Name | Role | Department |
|------|------|------------|
| Alice | Developer | Engineering |
| Bob | Designer | Product |
| Carol | Manager | Operations |

Aligned Columns

| Left | Center | Right |
|:-----|:------:|------:|
| L1 | C1 | R1 |
| L2 | C2 | R2 |
| L3 | C3 | R3 |

Feature Comparison

| Feature | Free | Pro | Enterprise |
|---------|:----:|:---:|:----------:|
| Users | 1 | 10 | Unlimited |
| Storage | 1GB | 100GB | 1TB |
| Support | ❌ | ✅ | ✅ |
| SSO | ❌ | ❌ | ✅ |
| API Access | ❌ | ✅ | ✅ |

Advanced Formatting

Blockquotes

> **Important:** This is a highlighted note.
> 
> It can span multiple lines and include:
> - Lists
> - **Bold text**
> - `code snippets`

Nested Lists

1. First item
   - Sub-item A
   - Sub-item B
     - Deep item 1
     - Deep item 2
2. Second item
   1. Numbered sub-item
   2. Another numbered sub-item
3. Third item

Task Lists

- [x] Complete documentation
- [x] Add examples
- [ ] Review and publish
- [ ] Announce release

Horizontal Rules

Section 1 content here.

---

Section 2 content here.

Batch Processing

Convert All Markdown Files

#!/bin/bash
# convert-all.sh

INPUT_DIR="docs"
OUTPUT_DIR="website"

mkdir -p "$OUTPUT_DIR"

for file in "$INPUT_DIR"/*.md; do
    basename=$(basename "$file" .md)
    mk2html "$file" -o "$OUTPUT_DIR/${basename}.html" --offline -q
    echo "✓ $basename.html"
done

Generate PDFs for Distribution

#!/bin/bash
# generate-pdfs.sh

mkdir -p dist/pdfs

mk2pdf README.md -o dist/pdfs/readme.pdf --page-size letter
mk2pdf docs/user-guide.md -o dist/pdfs/user-guide.pdf --page-size a4
mk2pdf docs/api-reference.md -o dist/pdfs/api-reference.pdf --page-size a4

echo "Generated $(ls dist/pdfs/*.pdf | wc -l) PDFs"

Watch and Convert (with entr)

# Install entr: brew install entr (macOS) or apt install entr (Linux)

# Watch for changes and auto-convert
ls docs/*.md | entr -r sh -c 'mk2html docs/index.md -o preview.html && echo "Updated at $(date)"'

Integration Examples

GitHub Actions

# .github/workflows/docs.yml
name: Build Documentation

on:
  push:
    branches: [main]
    paths: ['docs/**']

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Set up Python
        uses: actions/setup-python@v5
        with:
          python-version: '3.11'

      - name: Install mk2html
        run: pip install mk2html

      - name: Build HTML docs
        run: |
          mkdir -p website
          for file in docs/*.md; do
            mk2html "$file" -o "website/$(basename ${file%.md}).html" --offline
          done

      - name: Deploy to GitHub Pages
        uses: peaceiris/actions-gh-pages@v3
        with:
          github_token: ${{ secrets.GITHUB_TOKEN }}
          publish_dir: ./website

Makefile

# Makefile

DOCS_SRC := $(wildcard docs/*.md)
DOCS_HTML := $(DOCS_SRC:docs/%.md=website/%.html)
DOCS_PDF := $(DOCS_SRC:docs/%.md=dist/%.pdf)

.PHONY: all html pdf clean

all: html pdf

html: $(DOCS_HTML)

pdf: $(DOCS_PDF)

website/%.html: docs/%.md
    @mkdir -p website
    mk2html $< -o $@ --offline

dist/%.pdf: docs/%.md
    @mkdir -p dist
    mk2pdf $< -o $@ --page-size letter

clean:
    rm -rf website dist

serve: html
    cd website && python -m http.server 8000

Pre-commit Hook

#!/bin/bash
# .git/hooks/pre-commit

# Regenerate README.html before commit
if git diff --cached --name-only | grep -q "README.md"; then
    echo "Regenerating README.html..."
    mk2html README.md -o README.html --offline -q
    git add README.html
fi

Python Script Integration

#!/usr/bin/env python3
"""Generate documentation programmatically."""

import subprocess
from pathlib import Path

def convert_docs(input_dir: str, output_dir: str, format: str = "html"):
    """Convert all markdown files in a directory."""
    input_path = Path(input_dir)
    output_path = Path(output_dir)
    output_path.mkdir(parents=True, exist_ok=True)

    for md_file in input_path.glob("*.md"):
        if format == "html":
            output_file = output_path / f"{md_file.stem}.html"
            cmd = ["mk2html", str(md_file), "-o", str(output_file), "--offline"]
        else:
            output_file = output_path / f"{md_file.stem}.pdf"
            cmd = ["mk2pdf", str(md_file), "-o", str(output_file)]

        result = subprocess.run(cmd, capture_output=True, text=True)
        if result.returncode == 0:
            print(f"✓ {output_file.name}")
        else:
            print(f"✗ {md_file.name}: {result.stderr}")

if __name__ == "__main__":
    convert_docs("docs", "website", format="html")
    convert_docs("docs", "dist", format="pdf")