Communitygithub.com

MarkItDown - 文件转Markdown转换器

将文件和办公文档转换为Markdown格式。支持PDF、DOCX、PPTX、XLSX、图片(含OCR)、音频(含转录)、HTML、CSV、JSON、XML、ZIP包、YouTube链接、EPub等多种格式。

MarkItDown - 文件转Markdown转换器 是什么?

MarkItDown 是微软开发的一款Python工具,专门用于将各种文件格式转换为 Markdown。Markdown 格式对LLM友好,能有效节省Token,同时保留文档的结构化信息。该工具完美支持 Claude Code、Cursor、Codex等主流AI编程助手,让开发者可以直接在AI代码环境中处理文档转换需求。MarkItDown 支持超过15种文件格式,包括PDF、Office文档、图片(支持OCR文本识别)、音频(支持语音转录)、HTML网页、CSV/JSON/XML数据文件、ZIP压缩包、EPub电子书,甚至 YouTube 视频的字幕提取。开发者可以通过命令行或Python API轻松集成,还支持通过Azure文档智能服务增强PDF转换效果,或利用OpenRouter调用LLM生成详细的图片描述。该工具为科研论文转译、数据分析提取、多文档批量处理等场景提供了高效、灵活的解决方案。

兼容平台✓Claude Code✓Codex CLI~Cursor
npx skills add https://github.com/David-Li0406/meta-skill-evloving/tree/HEAD/AgentSkillOS/data/skill_seeds/markitdown

在你喜欢的 AI 中提问

打开一个已预加载此 Agent Skill 的新对话。

文档

MarkItDown - 文件转Markdown转换器 是做什么的?

概述

MarkItDown 是微软开发的Python工具,用于将各种文件格式转换为Markdown。该工具特别适合将文档转换为LLM友好的文本格式,因为Markdown对Token利用高效且能被现代语言模型很好理解。

主要优势:

  • 将文档转换为清晰、结构化的Markdown
  • 对LLM处理而言,Token效率高的格式
  • 支持15种以上文件格式
  • 可选AI增强图片描述
  • 支持图片和扫描文档的OCR
  • 支持音频文件的语音转录

科学示意图增强视觉呈现

使用此技能创建文档时,请始终考虑添加科学图表和示意图以增强视觉沟通效果。

如果您的文档尚未包含示意图或图表:

  • 使用 scientific-schematics 技能生成AI驱动的出版级图表
  • 只需用自然语言描述您想要的图表
  • Nano Banana Pro 将自动生成、审查并完善示意图

对于新文档: 应默认生成科学示意图,以直观展示文中描述的关键概念、工作流程、架构或关系。

如何生成示意图:

python scripts/generate_schematic.py "您的图表描述" -o figures/output.png

AI将自动:

  • 创建格式得当的出版级图片
  • 经过多次迭代审查和完善
  • 确保可访问性(色盲友好、高对比度)
  • 将输出保存在 figures/ 目录下

何时添加示意图:

  • 文档转换工作流图
  • 文件格式架构图
  • OCR处理流水线图
  • 集成工作流程图
  • 系统架构图
  • 数据流图
  • 任何受益于可视化的复杂概念

有关创建示意图的详细指南,请参阅 scientific-schematics 技能文档。


支持的格式

格式描述备注
PDF便携式文档格式全文提取
DOCXMicrosoft Word保留表格、格式
PPTXPowerPoint带注释的幻灯片
XLSXExcel 电子表格表格和数据
图片JPEG, PNG, GIF, WebPEXIF元数据 + OCR
音频WAV, MP3元数据 + 转录
HTML网页干净的转换
CSV逗号分隔值表格格式
JSONJSON数据结构化表示
XMLXML文档结构化格式
ZIP压缩文件迭代遍历内容
EPUB电子书全文提取
YouTube视频链接获取字幕

快速开始

安装

# 安装全部功能
pip install 'markitdown[all]'

# 或从源码安装
git clone https://github.com/microsoft/markitdown.git
cd markitdown
pip install -e 'packages/markitdown[all]'

命令行用法

# 基本转换
markitdown document.pdf > output.md

# 指定输出文件
markitdown document.pdf -o output.md

# 管道内容
cat document.pdf | markitdown > output.md

# 启用插件
markitdown --list-plugins  # 列出可用插件
markitdown --use-plugins document.pdf -o output.md

Python API

from markitdown import MarkItDown

# 基本用法
md = MarkItDown()
result = md.convert("document.pdf")
print(result.text_content)

# 从流转换
with open("document.pdf", "rb") as f:
    result = md.convert_stream(f, file_extension=".pdf")
    print(result.text_content)

高级功能

1. AI增强图片描述

通过OpenRouter使用LLM生成详细的图片描述(适用于PPTX和图片文件):

from markitdown import MarkItDown
from openai import OpenAI

# 初始化OpenRouter客户端(兼容OpenAI API)
client = OpenAI(
    api_key="your-openrouter-api-key",
    base_url="https://openrouter.ai/api/v1"
)

md = MarkItDown(
    llm_client=client,
    llm_model="anthropic/claude-sonnet-4.5",  # 推荐用于科学视觉理解
    llm_prompt="详细描述此图片内容,用于科学文档"
)

result = md.convert("presentation.pptx")
print(result.text_content)

2. Azure文档智能

使用Microsoft文档智能服务增强PDF转换:

# 命令行
markitdown document.pdf -o output.md -d -e "<document_intelligence_endpoint>"
# Python API
from markitdown import MarkItDown

md = MarkItDown(docintel_endpoint="<document_intelligence_endpoint>")
result = md.convert("complex_document.pdf")
print(result.text_content)

3. 插件系统

MarkItDown支持第三方插件扩展功能:

# 列出已安装插件
markitdown --list-plugins

# 启用插件
markitdown --use-plugins file.pdf -o output.md

在GitHub上使用标签 #markitdown-plugin 查找插件

可选依赖项

控制您支持的文件格式:

# 安装特定格式支持
pip install 'markitdown[pdf, docx, pptx]'

# 所有可选选项:
# [all]                  - 所有可选依赖项
# [pptx]                 - PowerPoint文件
# [docx]                 - Word文档
# [xlsx]                 - Excel电子表格
# [xls]                  - 旧版Excel文件
# [pdf]                  - PDF文档
# [outlook]              - Outlook邮件
# [az-doc-intel]         - Azure文档智能
# [audio-transcription]  - WAV和MP3转录
# [youtube-transcription] - YouTube视频转录

常见用例

1. 将科学论文转换为Markdown

from markitdown import MarkItDown

md = MarkItDown()

# 转换PDF论文
result = md.convert("research_paper.pdf")
with open("paper.md", "w") as f:
    f.write(result.text_content)

2. 从Excel提取数据用于分析

from markitdown import MarkItDown

md = MarkItDown()
result = md.convert("data.xlsx")

# 结果将采用Markdown表格格式
print(result.text_content)

3. 处理多个文档

from markitdown import MarkItDown
import os
from pathlib import Path

md = MarkItDown()

# 处理目录中的所有PDF
pdf_dir = Path("papers/")
output_dir = Path("markdown_output/")
output_dir.mkdir(exist_ok=True)

for pdf_file in pdf_dir.glob("*.pdf"):
    result = md.convert(str(pdf_file))
    output_file = output_dir / f"{pdf_file.stem}.md"
    output_file.write_text(result.text_content)
    print(f"已转换:{pdf_file.name}")

4. 使用AI描述转换PowerPoint

from markitdown import MarkItDown
from openai import OpenAI

# 使用OpenRouter访问多种AI模型
client = OpenAI(
    api_key="your-openrouter-api-key",
    base_url="https://openrouter.ai/api/v1"
)

md = MarkItDown(
    llm_client=client,
    llm_model="anthropic/claude-sonnet-4.5",  # 推荐用于演示文稿
    llm_prompt="详细描述此幻灯片图片,重点关注关键视觉元素和数据"
)

result = md.convert("presentation.pptx")
with open("presentation.md", "w") as f:
    f.write(result.text_content)

5. 批量转换不同格式

from markitdown import MarkItDown
from pathlib import Path

md = MarkItDown()

# 待转换的文件
files = [
    "document.pdf",
    "spreadsheet.xlsx",
    "presentation.pptx",
    "notes.docx"
]

for file in files:
    try:
        result = md.convert(file)
        output = Path(file).stem + ".md"
        with open(output, "w") as f:
            f.write(result.text_content)
        print(f"✓ 已转换 {file}")
    except Exception as e:
        print(f"✗ 转换 {file} 时出错:{e}")

6. 提取YouTube视频转录

from markitdown import MarkItDown

md = MarkItDown()

# 将YouTube视频转换为转录文本
result = md.convert("https://www.youtube.com/watch?v=VIDEO_ID")
print(result.text_content)

Docker用法

# 构建镜像
docker build -t markitdown:latest .

# 运行转换
docker run --rm -i markitdown:latest < ~/document.pdf > output.md

最佳实践

1. 选择合适的转换方法

  • 简单文档:使用基本的 MarkItDown()
  • 复杂PDF:使用Azure文档智能
  • 视觉内容:启用AI图片描述
  • 扫描文档:确保已安装OCR依赖项

2. 优雅地处理错误

from markitdown import MarkItDown

md = MarkItDown()

try:
    result = md.convert("document.pdf")
    print(result.text_content)
except FileNotFoundError:
    print("未找到文件")
except Exception as e:
    print(f"转换错误:{e}")

3. 高效处理大文件

from markitdown import MarkItDown

md = MarkItDown()

# 对于大文件,使用流式处理
with open("large_file.pdf", "rb") as f:
    result = md.convert_stream(f, file_extension=".pdf")
    
    # 分块处理或直接保存
    with open("output.md", "w") as out:
        out.write(result.text_content)

4. 优化Token效率

Markdown输出本身已对Token友好,但您可以:

  • 移除多余空白
  • 合并相似章节
  • 如果不需要,去除元数据
from markitdown import MarkItDown
import re

md = MarkItDown()
result = md.convert("document.pdf")

# 清理多余空白
clean_text = re.sub(r'\n{3,}', '\n\n', result.text_content)
clean_text = clean_text.strip()

print(clean_text)

与科学工作流集成

转换文献用于综述

from markitdown import MarkItDown
from pathlib import Path

md = MarkItDown()

# 转换literature文件夹中的所有论文
papers_dir = Path("literature/pdfs")
output_dir = Path("literature/markdown")
output_dir.mkdir(exist_ok=True)

for paper in papers_dir.glob("*.pdf"):
    result = md.convert(str(paper))
    
    # 保存并附带元数据
    output_file = output_dir / f"{paper.stem}.md"
    content = f"# {paper.stem}\n\n"
    content += f"**来源**:{paper.name}\n\n"
    content += "---\n\n"
    content += result.text_content
    
    output_file.write_text(content)

# AI增强转换(含图表)
from openai import OpenAI

client = OpenAI(
    api_key="your-openrouter-api-key",
    base_url="https://openrouter.ai/api/v1"
)

md_ai = MarkItDown(
    llm_client=client,
    llm_model="anthropic/claude-sonnet-4.5",
    llm_prompt="以技术精度描述科学图表"
)

提取表格用于分析

from markitdown import MarkItDown
import re

md = MarkItDown()
result = md.convert("data_tables.xlsx")

# Markdown表格可以直接解析或使用
print(result.text_content)

故障排除

常见问题

  1. 缺少依赖项:安装特定功能的包

    pip install 'markitdown[pdf]'  # 确保PDF支持
    
  2. 二进制文件错误:确保以二进制模式打开文件

    with open("file.pdf", "rb") as f:  # 注意 "rb"
        result = md.convert_stream(f, file_extension=".pdf")
    
  3. OCR不工作:安装tesseract

    # macOS
    brew install tesseract
    
    # Ubuntu
    sudo apt-get install tesseract-ocr
    

性能考量

  • PDF文件:大型PDF可能需要时间;如果支持,可考虑页范围
  • 图片OCR:OCR处理对CPU要求高
  • 音频转录:需要额外的计算资源
  • AI图片描述:需要API调用(可能产生费用)

下一步

  • 参见 references/api_reference.md 获取完整API文档
  • 查看 references/file_formats.md 了解格式特定细节
  • 阅读 scripts/batch_convert.py 获取自动化示例
  • 探索 scripts/convert_with_ai.py 获取AI增强转换

资源

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

David-Li0406/meta-skill-evloving

Browser automation with persistent page state. Use when users ask to navigate websites, fill forms, take screenshots, extract web data, test web apps, or automate browser workflows. Trigger phrases include "go to [url]", "click on", "fill out the form", "take a screenshot", "scrape", "automate", "test the website", "log into", or any browser interaction request.

David-Li0406/meta-skill-evloving

Create technical diagrams using Mermaid syntax for architecture, sequences, ERDs, flowcharts, and state machines. Use for visualizing system design, data flows, and processes. Triggers: diagram, mermaid, architecture diagram, sequence diagram, flowchart, ERD, entity relationship, state diagram, C4 model, component diagram, visualize, draw.

David-Li0406/meta-skill-evloving

Comprehensive document creation, editing, and analysis with support for tracked changes, comments, formatting preservation, and text extraction. When Claude needs to work with professional documents (.docx files) for: (1) Creating new documents, (2) Modifying or editing content, (3) Working with tracked changes, (4) Adding comments, or any other document tasks

David-Li0406/meta-skill-evloving

Complete color manipulation and green screen effects system. PROACTIVELY activate for: (1) Green screen/chromakey removal, (2) Color grading with LUTs, (3) Color correction (levels, curves, white balance), (4) Colorkey/color removal effects, (5) Hue/saturation manipulation, (6) Color space conversions (BT.709, BT.2020, HDR), (7) Color isolation effects, (8) Teal and orange look, (9) Vintage/film looks, (10) Color keying for transparency. Provides: chromakey and colorkey filters, LUT application (lut3d), curves and levels adjustment, color balance, selective color manipulation, color space handling, HDR tone mapping, professional color grading chains.

David-Li0406/meta-skill-evloving

Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when building MCP servers to integrate external APIs or services, whether in Python (FastMCP) or Node/TypeScript (MCP SDK).

David-Li0406/meta-skill-evloving

Build with OpenAI's stateless APIs - Chat Completions (GPT-5, GPT-4o), Embeddings, Images (DALL-E 3), Audio (Whisper + TTS), and Moderation. Includes Node.js SDK and fetch-based approaches for Cloudflare Workers. Use when: implementing chat completions with GPT-5/GPT-4o, streaming responses with SSE, using function calling/tools, creating structured outputs with JSON schemas, generating embeddings for RAG (text-embedding-3-small/large), generating images with DALL-E 3, editing images with GPT-Image-1, transcribing audio with Whisper, synthesizing speech with TTS (11 voices), moderating content (11 safety categories), or troubleshooting rate limits (429), invalid API keys (401), function calling failures, streaming parse errors, embeddings dimension mismatches, or token limit exceeded.

David-Li0406/meta-skill-evloving

Comprehensive PDF manipulation toolkit for extracting text and tables, creating new PDFs, merging/splitting documents, and handling forms. When Claude needs to fill in a PDF form or programmatically process, generate, or analyze PDF documents at scale.

David-Li0406/meta-skill-evloving

Presentation creation, editing, and analysis. When Claude needs to work with presentations (.pptx files) for: (1) Creating new presentations, (2) Modifying or editing content, (3) Working with layouts, (4) Adding comments or speaker notes, or any other presentation tasks

David-Li0406/meta-skill-evloving

Comprehensive spreadsheet creation, editing, and analysis with support for formulas, formatting, data analysis, and visualization. When Claude needs to work with spreadsheets (.xlsx, .xlsm, .csv, .tsv, etc) for: (1) Creating new spreadsheets with formulas and formatting, (2) Reading or analyzing data, (3) Modify existing spreadsheets while preserving formulas, (4) Data analysis and visualization in spreadsheets, or (5) Recalculating formulas

David-Li0406/meta-skill-evloving

Download YouTube videos with customizable quality and format options. Use this skill when the user asks to download, save, or grab YouTube videos. Supports various quality settings (best, 1080p, 720p, 480p, 360p), multiple formats (mp4, webm, mkv), and audio-only downloads as MP3.

David-Li0406/meta-skill-evloving

Best practices for Remotion - Video creation in React

David-Li0406/meta-skill-evloving

Provides bidirectional translation (Chinese/English), grammar checking, and sentence polishing. Supports specific tense constraints, context-aware tone adjustment, and natural expression optimization. Outputs direct text without formatting.

David-Li0406/meta-skill-evloving

指导如何通过自定义注解(如@Unicom)标识Dubbo接口,利用BeanDefinitionRegistryPostProcessor在启动时扫描并动态注册ReferenceBean,实现RPC调用的封装。

David-Li0406/meta-skill-evloving

生成Python脚本,利用FFmpeg将图片序列按3x3布局合并,或将合并图拆分。要求使用subprocess模块执行命令,并支持用户交互式输入路径。

David-Li0406/meta-skill-evloving

SOP for extracting and analyzing promotional activity details, handling time formatting, location mapping, payment logic, and step-by-step process validation.

David-Li0406/meta-skill-evloving

Specializes in creating TikTok short video scripts using an anthropomorphic 'Chef' perspective to explain wildlife food chains and survival environments, utilizing real field footage.

David-Li0406/meta-skill-evloving

针对TikTok平台,以拟人化视角(如动物作为厨师)创作系列短视频脚本。重点介绍野生动物、食物链及生态环境,要求使用野外实拍素材,风格幽默且具有教育意义。

David-Li0406/meta-skill-evloving

Generates KWL (Know, Want to know, Learned) charts for educational videos, specifically BrainPOP, using simple 7th-grade language and short, concise bullet points.

David-Li0406/meta-skill-evloving

Develops DAX measures to calculate promo and regular volumes and generates a calculated table of dates excluding continuous promo date ranges, handling multiple periods and nulls.

David-Li0406/meta-skill-evloving

Tracks complex, multi-session work using the Beads issue tracker and dependency graphs, and provides persistent memory that survives conversation compaction. Use when work spans multiple sessions, has complex dependencies, or needs persistent context across compaction cycles. Trigger with phrases like "create task for", "what's ready to work on", "show task", "track this work", "what's blocking", or "update status".

相关技能