@docen/import-docx

中文文档
0.2.9发布于 2026/04/27MITTypeScriptES Module近 30 天下载 7887

A powerful TipTap/ProseMirror extension that imports Microsoft Word DOCX files to editor content

此软件包已被标记为弃用

Deprecated: merged into @docen/docx — use @docen/docx for DOCX parse/generate.

原始使用文档
文档目录28 节
  1. Features
  2. Installation
  3. Quick Start
  4. API Reference
  5. parseDOCX(input, options?)
  6. Supported Content Types
  7. Text Formatting
  8. Block Elements
  9. Lists
  10. Tables
  11. Media & Embeds
  12. Parsing Algorithm
  13. Document Structure
  14. Table Processing
  15. List Processing
  16. Examples
  17. Basic Usage
  18. Use with TipTap Editor
  19. Node.js Environment with Image Cropping
  20. Disable Image Cropping
  21. Known Limitations
  22. Blockquote Detection
  23. Code Marks
  24. Color Format
  25. Image Limitations
  26. Table Cell Types
  27. Contributing
  28. License

@docen/import-docx

npm version npm downloads npm license

Import Microsoft Word DOCX files to TipTap/ProseMirror content.

Features

  • 📝 Rich Text Parsing - Accurate parsing of headings, paragraphs, and blockquotes with formatting
  • 🖼️ Image Extraction - Automatic image extraction with base64 conversion and cropping support
  • 📊 Table Support - Complete table structure with colspan/rowspan detection algorithm
  • ✅ Lists & Tasks - Bullet lists, numbered lists with start number extraction, and task lists with checkbox detection
  • 🎨 Text Formatting - Bold, italic, underline, strikethrough, subscript, superscript, and highlights
  • 🎯 Text Styles - Comprehensive style support including colors, backgrounds, fonts, sizes, and line heights
  • 🔗 Links - Hyperlink extraction with href preservation
  • 💻 Code Blocks - Code block detection with language attribute extraction
  • 🌐 Cross-Platform - Works in both browser and Node.js environments
  • ✂️ Image Cropping - Crop metadata preservation with optional physical cropping
  • 🧠 Smart Parsing - DOCX XML parsing with proper element grouping and structure reconstruction
  • ⚡ Fast Processing - Uses fflate for ultra-fast ZIP decompression

Installation

# Install with npm
$ npm install @docen/import-docx

# Install with yarn
$ yarn add @docen/import-docx

# Install with pnpm
$ pnpm add @docen/import-docx

Quick Start

import { parseDOCX } from "@docen/import-docx";
import { readFileSync } from "node:fs";

// Read DOCX file
const buffer = readFileSync("document.docx");

// Parse DOCX to TipTap JSON
const content = await parseDOCX(buffer);

// Use in TipTap editor
editor.commands.setContent(content);

API Reference

parseDOCX(input, options?)

Parses a DOCX file and converts it to TipTap/ProseMirror JSON content.

Parameters:

  • input: Buffer | ArrayBuffer | Uint8Array - DOCX file data
  • options?: DocxImportOptions - Optional import configuration

Returns: Promise<JSONContent> - TipTap/ProseMirror document content with images embedded

Options:

interface DocxImportOptions {
  image?: {
    /** Custom image handler (default: embed as base64) */
    handler?: (info: DocxImageInfo) => Promise<DocxImageResult>;

    /**
     * Dynamic import function for @napi-rs/canvas
     * Required for image cropping in Node.js environment, ignored in browser
     */
    canvasImport?: () => Promise<typeof import("@napi-rs/canvas")>;

    /**
     * Enable or disable physical image cropping during import
     * When true, images with crop information in DOCX will be physically cropped
     * When false (default), crop metadata is preserved but full image is used
     *
     * @default false
     */
    crop?: boolean;
  };

  paragraph?: {
    /** Whether to ignore empty paragraphs (default: false) */
    ignoreEmpty?: boolean;
  };
}

Default Image Converter:

The package exports defaultImageConverter which embeds images as base64 data URLs:

import { parseDOCX, defaultImageConverter } from "@docen/import-docx";

await parseDOCX(buffer, {
  image: {
    handler: async (info) => {
      if (shouldUploadToCDN) {
        return { src: await uploadToCDN(info.data) };
      }
      return defaultImageConverter(info);
    },
  },
});

Supported Content Types

Text Formatting

  • Bold, Italic, Underline, Strikethrough
  • ^Superscript^ and Subscript
  • Text highlights
  • Text colors and background colors
  • Font families and sizes
  • Line heights

Block Elements

  • Headings (H1-H6) with proper level detection
  • Paragraphs with text alignment (left, right, center, justify)
  • Blockquotes (Detected by indentation + left border formatting)
  • Horizontal Rules (Detected as page breaks in DOCX)
  • Code Blocks with language attribute support

Lists

  • Bullet Lists with proper nesting and structure
  • Numbered Lists with custom start number extraction
  • Task Lists with checked/unchecked state detection (☐/☑ symbols)

Tables

  • Complete table structure parsing
  • Table Cells with colspan detection using grid-based algorithm
  • Table Cells with rowspan detection using vMerge tracking
  • Cell alignment and formatting preservation
  • Merged cell handling (both horizontal and vertical)

Media & Embeds

  • Images with automatic base64 conversion
  • Grouped Images (DOCX image groups) support
  • Links (hyperlinks) with href extraction

Parsing Algorithm

Document Structure

The parser follows a structured workflow:

  1. Extract Relationships - Parse _rels/document.xml.rels for hyperlinks and images
  2. Parse Numbering - Extract list definitions from numbering.xml (abstractNum → numFmt)
  3. Process Document Body - Iterate through document.xml elements:
    • Detect content types (tables, lists, paragraphs, code blocks, etc.)
    • Group consecutive elements into proper containers
    • Convert XML nodes to TipTap JSON nodes

Table Processing

Tables use specialized algorithms:

  • Colspan Detection - Grid-based algorithm tracks cell positions and detects horizontal merges
  • Rowspan Detection - Vertical merge (vMerge) tracking across rows with proper cell skipping
  • Cell Content - Recursive parsing of nested paragraphs and formatting
  • Hyperlink Support - Proper handling of links within table cells

List Processing

Lists utilize the DOCX numbering system:

  • Numbering ID Mapping - Maps abstractNum to formatting (bullet vs decimal)
  • Start Value Extraction - Extracts and preserves start numbers for ordered lists
  • Nesting Preservation - Maintains proper list hierarchy
  • Consecutive Grouping - Groups consecutive list items into list containers

Examples

Basic Usage

import { parseDOCX } from "@docen/import-docx";

const buffer = readFileSync("example.docx");
const content = await parseDOCX(buffer);

console.log(JSON.stringify(content, null, 2));

Use with TipTap Editor

import { Editor } from "@tiptap/core";
import { parseDOCX } from "@docen/import-docx";

const editor = new Editor({
  extensions: [...],
  content: "",
});

// Import DOCX file
async function importDocx(file: File) {
  const buffer = await file.arrayBuffer();
  const content = await parseDOCX(buffer);
  editor.commands.setContent(content);
}

Node.js Environment with Image Cropping

To enable image cropping in Node.js environment, you need to provide @napi-rs/canvas:

import { parseDOCX } from "@docen/import-docx";
import { readFileSync } from "node:fs";

// Install @napi-rs/canvas first: pnpm add @napi-rs/canvas
const buffer = readFileSync("document.docx");

const content = await parseDOCX(buffer, {
  image: {
    canvasImport: () => import("@napi-rs/canvas"),
    crop: true, // Enable physical cropping (default is false)
  },
});

Note: By default, physical image cropping is disabled. Crop metadata is preserved in the output for round-trip conversion, but the full image data is used.

Disable Image Cropping

If you want to explicitly ignore crop information in DOCX and use full images (this is the default behavior):

const content = await parseDOCX(buffer, {
  image: {
    crop: false,
  },
});

Known Limitations

Blockquote Detection

DOCX does not have a semantic blockquote structure. Blockquotes are detected by:

  • Left indentation ≥ 720 twips (0.5 inch)
  • Presence of left border (single line)

This detection method may produce false positives for documents with custom indentation similar to blockquotes.

Code Marks

The code mark is NOT automatically detected from monospace fonts (Consolas, Courier New, etc.). This is intentional to avoid false positives. Code marks should be explicitly added in the source document or through editor UI.

Color Format

All colors are imported as hex values (e.g., "#FF0000", "#008000"). Color names from the original document are not preserved.

Image Limitations

  • Only embedded images are supported (external image links are not fetched)
  • Image dimensions and title are extracted from DOCX metadata
  • Image Cropping: By default, crop metadata is preserved but images are not physically cropped
    • To enable physical cropping, set image.crop: true in options
    • In browser environments, cropping works natively with Canvas API
    • In Node.js, you must also provide image.canvasImport option with dynamic import of @napi-rs/canvas
    • If @napi-rs/canvas is not available in Node.js, images will be imported without cropping (graceful degradation)
  • Some DOCX image features (like advanced positioning or text wrapping) have limited support

Table Cell Types

DOCX format does not distinguish between header and body cells at a semantic level. All cells are imported as tableCell type for consistency. This is a DOCX format limitation.

Contributing

Contributions are welcome! Please read our Contributor Covenant and submit pull requests to the main repository.

License

版本与发布记录

@docen/import-docx 共发布 31 个版本,首次发布于 2026/01/11;过去 12 个月发布了 31 个版本。

版本发布日期距今
0.2.9latest2026/04/276 个月前
0.2.82026/04/276 个月前
0.2.72026/04/276 个月前
0.2.62026/04/246 个月前
0.2.52026/04/246 个月前
0.2.42026/04/246 个月前

关于 @docen/import-docx 的常见问题

@docen/import-docx 是什么?

A powerful TipTap/ProseMirror extension that imports Microsoft Word DOCX files to editor content注意:该包已被作者标记为弃用——Deprecated: merged into @docen/docx — use @docen/docx for DOCX parse/generate.

如何安装 @docen/import-docx?

在项目目录运行 npm install @docen/import-docx,或使用 pnpm add / yarn add / bun add。

@docen/import-docx 支持 TypeScript 吗?

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

@docen/import-docx 支持 ESM 还是 CommonJS?

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

@docen/import-docx 可以商用吗?

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

@docen/import-docx 的下载量有多少?

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

@docen/import-docx 还在维护吗?

最新版本 0.2.9 发布于 2026/04/27(6 个月前);至今共发布 31 个版本,其中过去 12 个月发布了 31 个;首次发布于 2026/01/11。作者已将其标记为弃用,新项目建议寻找替代方案。