mcpField
M
md-to-office

md-to-office

github.com/claude-office-skills文档处理5455.2k 次安装39 周前更新
代码仓库

关于 md-to-office

md-to-office 是一项使用 Pandoc 将 Markdown 转换为 Office 及其他文档格式的技能,支持模板和多种转换选项,格式包括 Word、PowerPoint、PDF、HTML、LaTeX 和 EPUB。

主要功能

  1. 01将 Markdown 转为 DOCX、PPTX 和 PDF
  2. 02导出为 HTML、LaTeX 和 EPUB
  3. 03应用参考模板
  4. 04设置元数据和目录
  5. 05批量转换文件

适用场景

  1. 01将 Markdown 笔记转为 Word 文档
  2. 02根据 Markdown 创建 PowerPoint 幻灯片
  3. 03使用模板生成样式化 PDF

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/claude-office-skills/skills --skill md-to-office

安装后在 Claude Code 中输入/md-to-office确认已加载。

详细介绍

Markdown 转 Office 工具

概述

此工具使用通用文档转换器 Pandoc,将 Markdown 转换为各种 Office 格式。将 Markdown 文件转换为专业的 Word 文档、PowerPoint 演示文稿、PDF 等,同时保留格式和结构。

使用方法

  1. 提供 Markdown 内容或文件
  2. 指定目标格式(docx、pptx、pdf 等)
  3. 可选:提供用于设置样式的参考模板
  4. 我会使用 Pandoc 和最佳设置进行转换

提示词示例:

  • “将此 README.md 转换为专业的 Word 文档”
  • “将我的 markdown 笔记转换为 PowerPoint 演示文稿”
  • “使用自定义样式从此 markdown 生成 PDF”
  • “使用公司模板将此 markdown 制作为 Word 文档”

领域知识

Pandoc 基础知识
# Basic conversion
pandoc input.md -o output.docx
pandoc input.md -o output.pdf
pandoc input.md -o output.pptx

# With template
pandoc input.md --reference-doc=template.docx -o output.docx

# Multiple inputs
pandoc ch1.md ch2.md ch3.md -o book.docx
支持的转换
FromToCommand
MarkdownWordpandoc in.md -o out.docx
MarkdownPDFpandoc in.md -o out.pdf
MarkdownPowerPointpandoc in.md -o out.pptx
MarkdownHTMLpandoc in.md -o out.html
MarkdownLaTeXpandoc in.md -o out.tex
MarkdownEPUBpandoc in.md -o out.epub
Markdown 转 Word(.docx)
基本转换
pandoc document.md -o document.docx
使用模板(参考文档)
# First create a template by converting sample
pandoc sample.md -o reference.docx

# Edit reference.docx styles in Word, then use it
pandoc input.md --reference-doc=reference.docx -o output.docx
添加目录
pandoc document.md --toc --toc-depth=3 -o document.docx
添加元数据
pandoc document.md \
  --metadata title="My Report" \
  --metadata author="John Doe" \
  --metadata date="2024-01-15" \
  -o document.docx
Markdown 转 PDF
通过 LaTeX(质量最佳)
# Requires LaTeX installation
pandoc document.md -o document.pdf

# With custom settings
pandoc document.md \
  --pdf-engine=xelatex \
  -V geometry:margin=1in \
  -V fontsize=12pt \
  -o document.pdf
通过 HTML/wkhtmltopdf
pandoc document.md \
  --pdf-engine=wkhtmltopdf \
  --css=style.css \
  -o document.pdf
PDF 选项
pandoc document.md \
  -V papersize:a4 \
  -V geometry:margin=2cm \
  -V fontfamily:libertinus \
  -V colorlinks:true \
  --toc \
  -o document.pdf
Markdown 转 PowerPoint(.pptx)
基本转换
pandoc slides.md -o presentation.pptx
幻灯片的 Markdown 结构
---
title: Presentation Title
author: Author Name
date: January 2024
---

# Section Header (creates section divider)

## Slide Title

- Bullet point 1
- Bullet point 2
  - Sub-bullet

## Another Slide

Content here

::: notes
Speaker notes go here (not visible in slides)
:::

## Slide with Image

![Description](image.png){width=80%}

## Two Column Slide

:::::::::::::: {.columns}
::: {.column width="50%"}
Left column content
:::

::: {.column width="50%"}
Right column content
:::
::::::::::::::
使用模板
# Use corporate PowerPoint template
pandoc slides.md --reference-doc=template.pptx -o presentation.pptx
YAML Frontmatter

在 Markdown 顶部添加元数据:

---
title: "Document Title"
author: "Author Name"
date: "2024-01-15"
abstract: "Brief description"
toc: true
toc-depth: 2
numbersections: true
geometry: margin=1in
fontsize: 11pt
documentclass: report
---

# First Chapter
...
Python 集成
import subprocess
import os

def md_to_docx(input_path, output_path, template=None):
    """Convert Markdown to Word document."""
    cmd = ['pandoc', input_path, '-o', output_path]
    
    if template:
        cmd.extend(['--reference-doc', template])
    
    subprocess.run(cmd, check=True)
    return output_path

def md_to_pdf(input_path, output_path, **options):
    """Convert Markdown to PDF with options."""
    cmd = ['pandoc', input_path, '-o', output_path]
    
    if options.get('toc'):
        cmd.append('--toc')
    
    if options.get('margin'):
        cmd.extend(['-V', f"geometry:margin={options['margin']}"])
    
    subprocess.run(cmd, check=True)
    return output_path

def md_to_pptx(input_path, output_path, template=None):
    """Convert Markdown to PowerPoint."""
    cmd = ['pandoc', input_path, '-o', output_path]
    
    if template:
        cmd.extend(['--reference-doc', template])
    
    subprocess.run(cmd, check=True)
    return output_path
pypandoc(Python 封装器)
import pypandoc

# Simple conversion
output = pypandoc.convert_file('input.md', 'docx', outputfile='output.docx')

# With options
output = pypandoc.convert_file(
    'input.md', 
    'docx',
    outputfile='output.docx',
    extra_args=['--toc', '--reference-doc=template.docx']
)

# From string
md_content = "# Hello\n\nThis is markdown."
output = pypandoc.convert_text(md_content, 'docx', format='md', outputfile='output.docx')

最佳实践

  1. 使用模板:创建参考文档,确保品牌风格一致
  2. 规范标题结构:统一使用标题级别(幻灯片用 ##,章节用 #)
  3. 逐步测试:先转换小节,检查格式
  4. 包含元数据:使用 YAML frontmatter 设置文档属性
  5. 处理图片:使用相对路径并指定尺寸

常见模式

批量转换
import subprocess
from pathlib import Path

def batch_convert(input_dir, output_format, output_dir=None):
    """Convert all markdown files in a directory."""
    input_path = Path(input_dir)
    output_path = Path(output_dir) if output_dir else input_path
    
    for md_file in input_path.glob('*.md'):
        output_file = output_path / md_file.with_suffix(f'.{output_format}').name
        subprocess.run([
            'pandoc', str(md_file), '-o', str(output_file)
        ], check=True)
        print(f"Converted: {md_file.name} -> {output_file.name}")

batch_convert('./docs', 'docx', './output')
报告生成器
def generate_report(title, sections, output_path, template=None):
    """Generate Word report from structured data."""
    
    # Build markdown
    md_content = f"""---
title: "{title}"
date: "{datetime.now().strftime('%B %d, %Y')}"
---

"""
    for section_title, content in sections.items():
        md_content += f"# {section_title}\n\n{content}\n\n"
    
    # Write temp file
    with open('temp_report.md', 'w') as f:
        f.write(md_content)
    
    # Convert
    cmd = ['pandoc', 'temp_report.md', '-o', output_path, '--toc']
    if template:
        cmd.extend(['--reference-doc', template])
    
    subprocess.run(cmd, check=True)
    os.remove('temp_report.md')

示例

示例 1:技术文档
import subprocess

# Create comprehensive markdown
doc = """---
title: "API Documentation"
author: "Dev Team"
date: "2024-01-15"
toc: true
toc-depth: 2
---

# Introduction

This document describes the REST API for our service.

## Authentication

All API requests require an API key in the header:

Authorization: Bearer YOUR_API_KEY


## Endpoints

### GET /users

Retrieve all users.

**Response:**

| Field | Type | Description |
|-------|------|-------------|
| id | integer | User ID |
| name | string | Full name |
| email | string | Email address |

### POST /users

Create a new user.

**Request Body:**

```json
{
  "name": "John Doe",
  "email": "[email protected]"
}

错误代码

CodeMeaning
400Bad Request
401Unauthorized
404Not Found
500Server Error
"""

保存 Markdown

with open('api_docs.md', 'w') as f: f.write(doc)

转换为 Word

subprocess.run([ 'pandoc', 'api_docs.md', '-o', 'api_documentation.docx', '--toc', '--reference-doc', 'company_template.docx' ], check=True)

转换为 PDF

subprocess.run([ 'pandoc', 'api_docs.md', '-o', 'api_documentation.pdf', '--toc', '-V', 'geometry:margin=1in', '-V', 'fontsize=11pt' ], check=True)


### Example 2: Presentation from Markdown
```python
slides_md = """---
title: "Q4 Business Review"
author: "Sales Team"
date: "January 2024"
---

# Overview

## Agenda

- Q4 Performance Summary
- Regional Highlights
- 2024 Outlook
- Q&A

# Q4 Performance

## Key Metrics

- Revenue: $12.5M (+15% YoY)
- New Customers: 250
- Retention Rate: 94%

## Regional Performance

:::::::::::::: {.columns}
::: {.column width="50%"}
**North America**

- Revenue: $6.2M
- Growth: +18%
:::

::: {.column width="50%"}
**Europe**

- Revenue: $4.1M
- Growth: +12%
:::
::::::::::::::

# 2024 Outlook

## Strategic Priorities

1. Expand APAC presence
2. Launch new product line
3. Improve customer onboarding

## Revenue Targets

| Quarter | Target |
|---------|--------|
| Q1 | $13M |
| Q2 | $14M |
| Q3 | $15M |
| Q4 | $16M |

# Thank You

## Questions?

Contact: [email protected]
"""

with open('presentation.md', 'w') as f:
    f.write(slides_md)

subprocess.run([
    'pandoc', 'presentation.md',
    '-o', 'q4_review.pptx',
    '--reference-doc', 'company_slides.pptx'
], check=True)

限制

  • 复杂的 Word 格式可能无法完美转换
  • 转换为 PDF 需要 LaTeX 或 wkhtmltopdf
  • 不支持 PowerPoint 动画
  • 某些高级表格可能需要手动调整
  • 图片定位可能比较棘手

安装

# macOS
brew install pandoc

# Ubuntu/Debian
sudo apt-get install pandoc

# Windows
choco install pandoc

# Python wrapper
pip install pypandoc

资源

评论

支持 Markdown