@aidalinfo/office-to-markdown

中文文档
1.0.2发布于 2025/08/27MITTypeScriptES Module近 30 天下载 2847

Modern TypeScript library for converting Office documents (DOCX) to Markdown format, optimized for Bun runtime with enhanced table support and math equation conversion.

原始使用文档
文档目录34 节
  1. 🚀 Features
  2. 📦 Installation
  3. With Bun (recommended)
  4. With npm/yarn/pnpm
  5. Required Dependencies
  6. 🛠️ Conversion Workflow
  7. 🎯 Simple Usage
  8. Basic Conversion
  9. Advanced API
  10. Conversion from Different Sources
  11. ⚙️ Configuration Options
  12. 🔧 Technical Architecture
  13. Module Structure
  14. Conversion Pipeline
  15. Mathematical Equation Handling
  16. Supported Mathematical Elements
  17. 🎨 Advanced Usage Examples
  18. Error Handling
  19. Capability Checking
  20. Usage with Node.js
  21. 🧪 Testing and Validation
  22. Test Results
  23. Performance
  24. 🔧 Development
  25. Prerequisites
  26. Development Installation
  27. Available Scripts
  28. Testing
  29. 🚀 Roadmap
  30. 🤝 Contributing
  31. Contribution Process
  32. 📄 License
  33. 🙏 Acknowledgments
  34. 📞 Support

📄 @aidalinfo/office-to-markdown

npm version TypeScript Bun

A modern TypeScript library for converting Office documents (DOCX) to Markdown format, optimized for the Bun ecosystem with advanced support for mathematical equations and tables.

🔬 Created through reverse engineering of Microsoft's MarkItDown - A TypeScript reimplementation that brings Python's document conversion capabilities to the JavaScript/Bun ecosystem with enhanced performance and type safety.

🚀 Features

  • ✅ DOCX to Markdown conversion with structure preservation
  • ✅ Mathematical equation support (OMML → LaTeX)
  • ✅ Table handling with automatic formatting
  • ✅ Style preservation (bold, italic, headings)
  • ✅ Image processing with alt text
  • ✅ Simple and advanced API for different use cases
  • ✅ Robust error handling with specific error codes
  • ✅ Optimized performance with Bun runtime
  • ✅ Complete TypeScript types for better DX

📦 Installation

bun add @aidalinfo/office-to-markdown

With npm/yarn/pnpm

npm install @aidalinfo/office-to-markdown
# or
yarn add @aidalinfo/office-to-markdown
# or  
pnpm add @aidalinfo/office-to-markdown

Required Dependencies

The following dependencies are automatically installed:

  • mammoth - DOCX to HTML conversion
  • turndown - HTML to Markdown conversion
  • jszip - ZIP archive manipulation (DOCX)

🛠️ Conversion Workflow

The conversion process follows these steps:

  1. File Detection - MIME type and extension verification
  2. Preprocessing - DOCX content extraction and modification
  3. Math Processing - OMML → LaTeX conversion
  4. Main Conversion - DOCX → HTML via mammoth
  5. Post-processing - HTML → Markdown with custom rules

🎯 Simple Usage

Basic Conversion

import { docxToMarkdown } from '@aidalinfo/office-to-markdown';

// Simple file conversion
const markdown = await docxToMarkdown('./document.docx');
console.log(markdown);

Advanced API

import { OfficeToMarkdown } from '@aidalinfo/office-to-markdown';

const converter = new OfficeToMarkdown({
  headingStyle: 'atx',           // Use ## for headings
  preserveTables: true,          // Preserve tables
  convertMath: true,             // Convert equations to LaTeX
});

// Conversion with options
const result = await converter.convertDocx('./document.docx');
console.log('Title:', result.title);
console.log('Content:', result.markdown);

Conversion from Different Sources

import { OfficeToMarkdown } from '@aidalinfo/office-to-markdown';

const converter = new OfficeToMarkdown();

// From file path
const result1 = await converter.convert('./document.docx');

// From Buffer
const buffer = await Bun.file('./document.docx').arrayBuffer();
const result2 = await converter.convert(buffer);

// From Bun file
const file = Bun.file('./document.docx');
const result3 = await converter.convert(file);

// Batch processing
const results = await converter.convertMultiple([
  './doc1.docx',
  './doc2.docx',
  buffer
]);

⚙️ Configuration Options

OptionTypeDefaultDescription
headingStyle'atx' | 'setext''atx'Markdown heading style
preserveTablesbooleantruePreserve tables
convertMathbooleantrueConvert mathematical equations
styleMapstring-Custom mapping for mammoth

🔧 Technical Architecture

Module Structure

src/
├── converters/           # Document converters
│   ├── base-converter.ts    # Abstract base class
│   └── docx-converter.ts    # Specialized DOCX converter
├── preprocessing/        # Preliminary processing
│   └── docx-preprocessor.ts # DOCX preprocessing (math)
├── math/                # Mathematical processing
│   └── omml-processor.ts    # OMML → LaTeX converter
├── utils/               # Utilities
│   ├── html-to-markdown.ts # HTML → Markdown conversion
│   ├── file-detector.ts     # File type detection
│   └── error-handler.ts     # Error handling
└── types/               # TypeScript definitions
    ├── converter.ts         # Converter types
    ├── result.ts           # Result types
    └── stream-info.ts      # File info types

Conversion Pipeline

  1. File Detection - MIME type and extension verification
  2. Preprocessing - DOCX content extraction and modification
  3. Mathematical Processing - OMML → LaTeX conversion
  4. Main Conversion - DOCX → HTML via mammoth
  5. Post-processing - HTML → Markdown with custom rules

Mathematical Equation Handling

The equation conversion follows this process:

// OMML (Office Math Markup Language)
<m:f>
  <m:num>1</m:num>
  <m:den>2</m:den>
</m:f>

// ↓ Preprocessing

<w:r><w:t>$\frac{1}{2}$</w:t></w:r>

// ↓ Mammoth (HTML)

<p>$\frac{1}{2}$</p>

// ↓ Turndown (Markdown)

$\frac{1}{2}$

Supported Mathematical Elements

OMMLLaTeXDescription
<m:f>\frac{}{}Fractions
<m:sSup>^{}Exponents
<m:sSub>_{}Subscripts
<m:rad>\sqrt{}Square roots
<m:rad><m:deg>\sqrt[]{}Nth roots

🎨 Advanced Usage Examples

Error Handling

import { 
  OfficeToMarkdown, 
  FileConversionException, 
  UnsupportedFormatException 
} from '@aidalinfo/office-to-markdown';

async function convertSafely(filePath: string) {
  try {
    const converter = new OfficeToMarkdown();
    const result = await converter.convertDocx(filePath);
    return result.markdown;
  } catch (error) {
    if (error instanceof UnsupportedFormatException) {
      console.error('Unsupported format:', error.message);
    } else if (error instanceof FileConversionException) {
      console.error('Conversion error:', error.message);
    } else {
      console.error('Unexpected error:', error.message);
    }
    throw error;
  }
}

Capability Checking

import { OfficeToMarkdown } from '@aidalinfo/office-to-markdown';

const converter = new OfficeToMarkdown();

// Check supported types
const info = converter.getSupportedTypes();
console.log('Extensions:', info.extensions); // ['.docx']
console.log('MIME types:', info.mimeTypes);

// Check if a file is supported
const isSupported = await converter.isSupported('./document.pdf');
console.log('PDF supported:', isSupported); // false

// Get file information
const fileInfo = await converter.getFileInfo('./document.docx');
console.log('MIME type:', fileInfo.mimetype);
console.log('Supported:', fileInfo.supported);

Usage with Node.js

import { readFile } from 'fs/promises';
import { OfficeToMarkdown } from '@aidalinfo/office-to-markdown';

// From Node.js Buffer
const buffer = await readFile('./document.docx');
const converter = new OfficeToMarkdown();
const result = await converter.convert(buffer);

console.log(result.markdown);

🧪 Testing and Validation

Test Results

  • ✅ HTML → Markdown conversion with tables
  • ✅ File type detection (DOCX vs others)
  • ✅ OMML → LaTeX mathematical conversion
  • ✅ Error handling with specific codes
  • ✅ Complete pipeline tested with real documents

Performance

  • Speed: ~80ms for an average document (7KB)
  • Fidelity: Complete preservation of structure and content
  • Robustness: Graceful error handling with fallbacks

🔧 Development

Prerequisites

  • Bun >= 1.2.0 (recommended) or Node.js >= 20.0.0
  • TypeScript >= 4.5.0

Development Installation

git clone https://github.com/aidalinfo/extract-kit.git
cd extract-kit/packages/office-to-markdown
bun install

Available Scripts

bun run build          # Complete build (ESM + types)
bun run dev            # Development mode with watch
bun run clean          # Clean dist/ folder

Testing

# Basic functionality test
bun run src/test.ts

# Test with real DOCX file
bun run test-docx.ts "your-file.docx"

🚀 Roadmap

  • PPT/PPTX format support - Presentation conversion
  • XLS/XLSX format support - Spreadsheet conversion
  • Streaming API - Large file streaming processing
  • Plugin system - Support for custom converters
  • Web interface - Optional user interface
  • Embedded image support - Image extraction and conversion
  • CLI batch mode - Command-line interface

🤝 Contributing

Contributions are welcome! Please see our contribution guide.

Contribution Process

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

📄 License

This project is licensed under MIT - see the LICENSE file for details.

🙏 Acknowledgments

  • Inspired by Microsoft's MarkItDown project
  • Uses mammoth.js for DOCX → HTML conversion
  • Uses turndown for HTML → Markdown conversion
  • Optimized for Bun runtime

📞 Support


@aidalinfo/office-to-markdown

Simple, fast, and reliable DOCX to Markdown conversion ⚡

版本与发布记录

@aidalinfo/office-to-markdown 共发布 3 个版本,首次发布于 2025/08/11;过去 12 个月发布了 0 个版本。

版本发布日期距今
1.0.2latest2025/08/271.2 年前
1.0.12025/08/111.2 年前
1.0.02025/08/111.2 年前

关于 @aidalinfo/office-to-markdown 的常见问题

@aidalinfo/office-to-markdown 是什么?

Modern TypeScript library for converting Office documents (DOCX) to Markdown format, optimized for Bun runtime with enhanced table support and math equation conversion.

如何安装 @aidalinfo/office-to-markdown?

在项目目录运行 npm install @aidalinfo/office-to-markdown,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:typescript(>=4.5.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@aidalinfo/office-to-markdown 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@aidalinfo/office-to-markdown 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@aidalinfo/office-to-markdown 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=20.0.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@aidalinfo/office-to-markdown 可以商用吗?

@aidalinfo/office-to-markdown 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@aidalinfo/office-to-markdown 的下载量有多少?

根据 npm 官方下载统计,@aidalinfo/office-to-markdown 在 2026/10/05 – 2026/11/03 这 30 天内被下载 2,847 次,日均约 95 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@aidalinfo/office-to-markdown 还在维护吗?

最新版本 1.0.2 发布于 2025/08/27(1.2 年前);至今共发布 3 个版本,其中过去 12 个月发布了 0 个;首次发布于 2025/08/11。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。