---
title: "通过 REST API 导入 DOCX"
description: "了解如何通过 Conversion REST API 将 .docx 文件导入为 Tiptap JSON 格式。"
canonical_url: "https://tiptap.zhcndoc.com/conversion/import/docx/rest-api"
---

# 通过 REST API 导入 DOCX

了解如何通过 Conversion REST API 将 .docx 文件导入为 Tiptap JSON 格式。

- **1. 激活试用或订阅**

  在您的账户中开始 [免费试用](https://cloud.tiptap.dev/v2?trial=true) 或 [订阅起始计划](https://cloud.tiptap.dev/v2/billing)。
- **2. 配置 Convert 应用**

  使用带有 `aud: "Convert"` 的签名令牌对 REST 调用进行身份验证。请参阅 [身份验证](https://tiptap.zhcndoc.com/authentication.md)。

DOCX 导入 API 会将 `.docx` 文件转换为 Tiptap 的 JSON 格式。它使用与 [编辑器扩展](https://tiptap.zhcndoc.com/conversion/import/docx/editor-extension.md) 相同的转换服务，并生成完全相同的内容输出。

当您需要服务器端处理、访问脚注或尾注数据（这是扩展不会暴露的），或需要不经过 schema 过滤的原始 JSON 时，REST API 是更好的选择。如果您希望将内容直接加载到 Tiptap 编辑器中，并自动应用页眉和页脚，请改用 [编辑器扩展](https://tiptap.zhcndoc.com/conversion/import/docx/editor-extension.md)。

> **查看 Postman 集合:**
>
> 您还可以前往我们的 [Postman
> 集合](https://www.postman.com/tiptap-platform/workspace/tiptap-workspace/collection/33042171-bcc93ecb-8bad-4484-8cb0-d995ee23ae60) 体验 Document Conversion API。

## 导入 DOCX

`POST /v2/convert/import/docx`

`/v2/convert/import/docx` 端点将 `docx` 文件转换为 Tiptap 的 JSON 格式。用户可向该端点 `POST` 文档，并通过多种参数定制转换过程中对不同文档元素的处理方式。

### 示例（cURL）

```bash
curl -X POST "https://api.tiptap.dev/v2/convert/import/docx" \
    -H "Authorization: Bearer YOUR_TOKEN" \
    -F "file=@/path/to/your/file.docx" \
    -F 'imageUploadConfig={"url":"https://your-image-upload-endpoint.com","headers":{"Authorization":"Bearer your-upload-token"}}' \
    -F "prosemirrorNodes={\"nodeKey\":\"nodeValue\"}" \
    -F "prosemirrorMarks={\"markKey\":\"markValue\"}"
```

> **需要订阅:**
>
> 此端点需要有效的 Tiptap 订阅。更多详情请查看我们的 [定价页面](https://tiptap.dev/pricing)。

### 必需的请求头

| 名称              | 描述                                        |
| --------------- | ----------------------------------------- |
| `Authorization` | 用于验证请求的 JWT 令牌。示例：`Bearer your-jwt-token` |

### 请求体

| 名称                  | 类型                  | 描述                                                                                                                                                                                                                                                                                                                                                            |
| ------------------- | ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `file`              | `File`              | 要转换的文件                                                                                                                                                                                                                                                                                                                                                        |
| `imageUploadConfig` | `JSON string`       | 用于配置图片上传的 JSON 对象。包含 `url`（必需），以及可选的 `headers`、`method` 和 `queryParams`。完整结构请参见 [编辑器扩展文档](https://tiptap.zhcndoc.com/conversion/import/docx/editor-extension.md#image-upload-configuration)。                                                                                                                                                                  |
| `prosemirrorNodes`  | `Object string`     | 用于转换的自定义节点映射，[查看更多信息](https://tiptap.zhcndoc.com/conversion/import/docx/custom-node-mapping.md)。                                                                                                                                                                                                                                                              |
| `prosemirrorMarks`  | `Object string`     | 用于转换的自定义标记映射，[查看更多信息](https://tiptap.zhcndoc.com/conversion/import/docx/custom-mark-mapping.md)                                                                                                                                                                                                                                                               |
| `verbose`           | `string \| number`  | 一个配置属性，用于帮助您控制导入过程中诊断输出的级别。这对于调试或更深入了解转换过程中的发生情况尤其有用。更多信息请参见 [详细输出](#import-verbose-output)                                                                                                                                                                                                                                                                   |
| `extractCssStyles`  | `"true" \| "false"` | **实验性。** 当为 `"true"` 时，响应会包含一个 `cssStyles` 字段，其中 DOCX 样式目录会转换为与 CSS 兼容的键值对。默认值为 `"false"`。有关输出结构和注意事项，请参见 [CSS 样式提取](#css-style-extraction-experimental)。                                                                                                                                                                                                     |
| `placeholders`      | `JSON string`       | 可选将 Word 的 `PAGE` / `NUMPAGES` 字段代码在页眉和页脚中转换为标准 `{page}` / `{numpages}` 文本标记。发送 `{}`（空对象）可使用默认配置启用；发送 `{ "page"?: string, "total"?: string }` 可使用重命名映射启用（例如 `{"total":"pages"}` 会使 `NUMPAGES` 返回为 `{pages}`）；或发送 `false` 显式禁用。若省略（默认），则保留 Word 的缓存显示值作为纯文本。该行为与编辑器的 `Pages.configure({ placeholders })` 选项一致；编辑器扩展会自动将其转发到此处。请参见 [页码字段](#page-number-fields)。 |
| `documentName`      | `String`            | 目标 Tiptap Collaboration 文档名称。当请求中提供的令牌对此文档拥有 `Documents:Write` 权限时，服务会将导入的评论线程与 Document Server 协调，使其在导入时即处于实时状态。请参见 [评论](#comments-in-the-response)。可选；如果令牌缺少该权限或环境中没有 Document Server，则会被忽略。                                                                                                                                                                |

### 导入详细输出

DOCX 导入扩展提供了一个 `verbose` 配置属性，帮助您控制导入过程中的诊断输出级别。此功能特别适合调试或获取转换过程的更多细节。

`verbose` 属性是一个位掩码数字，用于决定输出哪些类型的日志信息。扩展使用以下级别：

| 值 | 级别      | 描述     |
| - | ------- | ------ |
| 1 | `log`   | 一般信息日志 |
| 2 | `warn`  | 警告     |
| 4 | `error` | 错误     |

> **详细输出位掩码:**
>
> 您可以通过将各级别的值相加来组合它们。例如，`verbose: 3` 将同时启用
> `log`（1）和 `warn`（2）消息。

详细输出会在返回的 `data` 属性外，增加一个名为 `logs` 的属性，包含 `info`、`warn` 和 `error` 三个数组，分别保存对应级别的日志信息。

```js
{
  "data": {
    "content": {
        // Tiptap JSON
    }
  },
  "logs": {
    "info": [],
    "warn": [
      {
        "message": "未在媒体文件中找到图片文件",
        "fileName": "image1.gif",
        "availableMediaFiles": []
      }
    ],
    "error": [
      {
        "message": "图片上传失败：一般错误",
        "fileName": "image1.gif",
        "url": "https://your-image-upload-endpoint.com",
        "error": "无法连接。计算机是否能够访问该 url？",
        "context": "uploadImage general error"
      }
    ]
  }
}
```

## 响应中的页眉与页脚

导入 API 会从 `.docx` 文件中提取页眉和页脚。当文档包含页眉或页脚内容时，响应的 `data` 对象会包含额外字段。

### 响应字段

| 字段                | 类型               | 描述                        |
| ----------------- | ---------------- | ------------------------- |
| `content`         | `Object`         | 主要文档正文，采用 Tiptap JSON 格式  |
| `header`          | `Object \| null` | 默认页眉内容，采用 Tiptap JSON 格式  |
| `footer`          | `Object \| null` | 默认页脚内容，采用 Tiptap JSON 格式  |
| `headerFirstPage` | `Object \| null` | 首页页眉（在 Word 中启用“首页不同”时）   |
| `footerFirstPage` | `Object \| null` | 首页页脚（在 Word 中启用“首页不同”时）   |
| `headerOdd`       | `Object \| null` | 奇数页页眉（在 Word 中启用“奇偶页不同”时） |
| `footerOdd`       | `Object \| null` | 奇数页页脚（在 Word 中启用“奇偶页不同”时） |
| `headerEven`      | `Object \| null` | 偶数页页眉（在 Word 中启用“奇偶页不同”时） |
| `footerEven`      | `Object \| null` | 偶数页页脚（在 Word 中启用“奇偶页不同”时） |

字段为 `null` 表示该文档未定义该特定页眉或页脚内容。

```json
{
  "data": {
    "content": {
      "type": "doc",
      "content": [
        {
          "type": "paragraph",
          "content": [{ "type": "text", "text": "文档主体内容..." }]
        }
      ]
    },
    "header": {
      "type": "doc",
      "content": [
        {
          "type": "paragraph",
          "content": [{ "type": "text", "text": "默认页眉" }]
        }
      ]
    },
    "footer": {
      "type": "doc",
      "content": [
        {
          "type": "paragraph",
          "content": [
            { "type": "text", "text": "第 " },
            { "type": "text", "text": "{page}" },
            { "type": "text", "text": " 页，共 " },
            { "type": "text", "text": "{numpages}" }
          ]
        }
      ]
    },
    "headerFirstPage": {
      "type": "doc",
      "content": [
        {
          "type": "paragraph",
          "content": [
            {
              "type": "text",
              "text": "封面页页眉",
              "marks": [{ "type": "bold" }]
            }
          ]
        }
      ]
    },
    "footerFirstPage": null,
    "headerOdd": null,
    "footerOdd": null,
    "headerEven": null,
    "footerEven": null
  }
}
```

导入 API 会从 `.docx` 文件中提取脚注和尾注。当文档包含脚注或尾注内容时，响应的 `data` 对象会包含额外字段。

### 页码字段

默认情况下，页眉和页脚中的 Word `PAGE` 和 `NUMPAGES` 字段代码会作为 Word 在文档上次打开时保存的缓存显示值导入（例如字面文本 `1`）。在请求中传入 `placeholders={}`，即可改为将这些字段转换为规范文本标记：`PAGE` 对应 `{page}`，`NUMPAGES` 对应 `{numpages}`。当识别到字段指令时，缓存的数值会被丢弃。

```bash
curl -X POST "https://api.tiptap.dev/v2/convert/import/docx" \
    -H "Authorization: Bearer YOUR_TOKEN" \
    -H "X-App-Id: YOUR_APP_ID" \
    -F "file=@/path/to/your/file.docx" \
    -F "placeholders={}"
```

下游消费者（例如 [Pages 扩展](https://tiptap.zhcndoc.com/pages/getting-started/overview.md)）会根据其配置中可识别的标记名称替换 `{page}` 和 `{numpages}`。要让传输格式匹配自定义标记注册表，请将 `placeholders` 作为包含 `page` 和/或 `total` 键的 JSON 对象传入：

```bash
curl -X POST "https://api.tiptap.dev/v2/convert/import/docx" \
    -H "Authorization: Bearer YOUR_TOKEN" \
    -H "X-App-Id: YOUR_APP_ID" \
    -F "file=@/path/to/your/file.docx" \
    -F 'placeholders={"page":"page","total":"total"}'
```

上面的示例将 `NUMPAGES` 映射为 `{total}`（Pages 对总页数字段使用的默认名称），因此编辑器预览可原生替换，无需任何配置。传输字段直接反映 `Pages.configure({ placeholders })`，并且在安装 Pages 扩展时，[编辑器扩展](https://tiptap.zhcndoc.com/conversion/import/docx/editor-extension.md) 会自动将其转发到这里。

## 响应中的脚注与尾注

| 字段          | 类型       | 说明                                                                     |
| ----------- | -------- | ---------------------------------------------------------------------- |
| `footnotes` | `Object` | 以脚注 ID 为键的对象，每个值是一个 Tiptap JSON 文档 (`{ type: "doc", content: [...] }`) |
| `endnotes`  | `Object` | 以尾注 ID 为键的对象，每个值是一个 Tiptap JSON 文档 (`{ type: "doc", content: [...] }`) |

不包含脚注或尾注的文档会返回空对象 (`{}`)，因此不会影响现有集成。

| 字段          | 类型       | 说明                                                                     |
| ----------- | -------- | ---------------------------------------------------------------------- |
| `footnotes` | `Object` | 以脚注 ID 为键的对象，每个值是一个 Tiptap JSON 文档 (`{ type: "doc", content: [...] }`) |
| `endnotes`  | `Object` | 以尾注 ID 为键的对象，每个值是一个 Tiptap JSON 文档 (`{ type: "doc", content: [...] }`) |

### 响应示例

```json
{
  "data": {
    "content": {
      "type": "doc",
      "content": [
        {
          "type": "paragraph",
          "content": [
            { "type": "text", "text": "这句话有一个脚注" },
            { "type": "footnoteReference", "attrs": { "noteId": "1" } },
            { "type": "text", "text": " 和一个尾注" },
            { "type": "endnoteReference", "attrs": { "noteId": "1" } },
            { "type": "text", "text": "。" }
          ]
        }
      ]
    },
    "footnotes": {
      "1": {
        "type": "doc",
        "content": [
          {
            "type": "paragraph",
            "content": [{ "type": "text", "text": "这是脚注内容。" }]
          }
        ]
      }
    },
    "endnotes": {
      "1": {
        "type": "doc",
        "content": [
          {
            "type": "paragraph",
            "content": [{ "type": "text", "text": "这是尾注内容。" }]
          }
        ]
      }
    },
    "header": null,
    "footer": null,
    "headerFirstPage": null,
    "footerFirstPage": null,
    "headerOdd": null,
    "footerOdd": null,
    "headerEven": null,
    "footerEven": null
  }
}
```

## 响应中的评论

导入 API 会从 `.docx` 文件中提取评论线程。当文档包含评论时，响应 `data` 对象会包含一个 `commentThreads` 数组。文档正文中的 `inlineThread` 标记（以及 `blockThread` 节点）带有 `data-thread-id`，其值与每个线程的 `id` 匹配，因此你可以将每个线程关联回它所注释的文本。

### 响应字段

| 字段                           | 类型        | 描述                                                                            |
| ---------------------------- | --------- | ----------------------------------------------------------------------------- |
| `commentThreads`             | `Array`   | 每个评论线程对应一项。文档没有评论时为空（或省略）。                                                    |
| `commentThreads[].id`        | `String`  | 线程 id。与 `content` 中线程的 `inlineThread` / `blockThread` 上的 `data-thread-id` 对应。 |
| `commentThreads[].durableId` | `String`  | Word 稳定的持久 id（如存在）。                                                           |
| `commentThreads[].resolved`  | `Boolean` | 该线程是否已解决。                                                                     |
| `commentThreads[].messages`  | `Array`   | 线程中的消息，先是根消息，然后按日期升序排列的回复。                                                    |
| `messages[].wId`             | `String`  | 评论原始 DOCX `w:id`。                                                             |
| `messages[].id`              | `String`  | Document Server 生成的评论 id。仅在协调后存在（见下文）。                                        |
| `messages[].durableId`       | `String`  | 规范化的持久 id（如存在）。                                                               |
| `messages[].body`            | `Object`  | 以 Tiptap JSON 表示的消息正文。                                                        |
| `messages[].data`            | `Object`  | 作者和日期元数据：`author`、`initials?`、`providerId?`、`userId?`、`dateIso?`、`dateUtc?`。  |

没有评论的文档会返回空的 `commentThreads` 数组，因此现有集成不会受到影响。`/import/docx` 和通用的 `/import` 都会返回相同的数据。

### 与 Document Server 的协调

默认情况下，返回的线程和消息 id 都源自 DOCX，且线程 `id` 会与 `content` 中的 `data-thread-id` 标记对应，因此客户端可以自行持久化这些线程。

如果在请求中传入 `documentName`，并且该请求的令牌授予了该文档的 `Documents:Write` 权限，服务就会将导入的评论与 Document Server 进行协调：它会在该处创建或更新线程，然后把返回的 `commentThreads` 以及正文标记都重写为服务器生成的 id。结果是在导入时就得到实时评论，并且 `messages[].id` 会被填充。当 `documentName` 缺失、令牌没有 `Documents:Write` 权限，或运行环境未暴露 Document Server 时，会跳过协调，并原样返回基于 DOCX 的 id。

### 示例响应

```json
{
  "data": {
    "content": {
      "type": "doc",
      "content": [
        {
          "type": "paragraph",
          "content": [
            {
              "type": "text",
              "text": "Reviewed text",
              "marks": [{ "type": "inlineThread", "attrs": { "data-thread-id": "abc123" } }]
            }
          ]
        }
      ]
    },
    "commentThreads": [
      {
        "id": "abc123",
        "resolved": false,
        "messages": [
          {
            "wId": "0",
            "body": {
              "type": "doc",
              "content": [
                {
                  "type": "paragraph",
                  "content": [{ "type": "text", "text": "Please cite a source." }]
                }
              ]
            },
            "data": {
              "author": "Ada Lovelace",
              "initials": "AL",
              "dateIso": "2026-01-01T10:30:00Z",
              "dateUtc": "2026-01-01T10:30:00Z"
            }
          }
        ]
      }
    ]
  }
}
```

## CSS 样式提取（实验性）

> **实验性功能:**
>
> `extractCssStyles` 为可选开启且处于实验阶段。响应的结构可能会在不另行通知的情况下发生变化。如果您依赖它，请锁定精确的客户端版本，并阅读 [CSS 注入文档](https://tiptap.zhcndoc.com/conversion/import/docx/css-injection.md) 以了解支持的选择器、CSS 属性和已知限制的完整列表。

在请求中传入 `extractCssStyles=true`，即可使响应包含一个 `cssStyles` 字段。该字段包含将 DOCX 默认样式目录转换为兼容 CSS 的键/值对，并以 CSS 选择器为键。

### 请求

```bash
curl -X POST "https://api.tiptap.dev/v2/convert/import/docx" \
    -H "Authorization: Bearer YOUR_TOKEN" \
    -H "X-App-Id: YOUR_APP_ID" \
    -F "file=@/path/to/your/file.docx" \
    -F "extractCssStyles=true"
```

### 响应字段

| Field       | Type     | Description                                                                                                                                                                                                                                             |
| ----------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `cssStyles` | `Object` | An object keyed by CSS selector, where each value is an object of CSS properties. Empty (`{}`) when the document has no extractable default styles. The field is omitted from the response entirely when `extractCssStyles` is not set or is `"false"`. |

### 支持的选择器

提取器会将 DOCX 命名样式映射到以下固定的 CSS 选择器集合。与映射不匹配的样式不会被转换。

`p`, `h1`, `h2`, `h3`, `h4`, `h5`, `h6`, `blockquote`, `ul li`, `ol li`, `strong`, `em`, `u`, `s`, `a`, `code`

### 支持的 CSS 属性

以上每个选择器都可以携带以下属性的任意子集，具体取决于 DOCX 中定义的样式。

`color`, `fontSize`, `fontFamily`, `fontWeight`, `fontStyle`, `textDecoration`, `backgroundColor`, `textAlign`, `marginTop`, `marginBottom`, `lineHeight`

### 示例响应

```json
{
  "data": {
    "content": {
      "type": "doc",
      "content": [
        {
          "type": "paragraph",
          "content": [{ "type": "text", "text": "Document body..." }]
        }
      ]
    },
    "cssStyles": {
      "p": {
        "fontSize": "16px",
        "fontFamily": "Calibri",
        "lineHeight": 1.15,
        "marginBottom": "8pt"
      },
      "h1": {
        "fontSize": "28px",
        "fontWeight": "bold",
        "color": "#1F3864",
        "marginTop": "24pt",
        "marginBottom": "6pt"
      },
      "a": {
        "color": "#0563C1",
        "textDecoration": "underline"
      },
      "blockquote": {
        "fontStyle": "italic",
        "color": "#595959"
      }
    }
  }
}
```

关于输出的说明：

- **值为字符串或数字。** 基于像素的属性（`fontSize`）会输出为 `"Npx"` 字符串；基于磅的间距（`marginTop`、`marginBottom`）会输出为 `"Npt"`；无单位的乘数（`auto` 行规则下的 `lineHeight`）会输出为普通数字。
- **样式继承已解析。** 子 DOCX 样式会包含其从父样式继承的所有内容（通过 `basedOn`）；输出会被扁平化，因此您无需沿链向上遍历。
- **支持本地化文档。** 非英语版 Word 中的命名样式会在输出前映射回其规范选择器。
- **缺失字段表示“未定义”。** 只有在至少提取到一个属性时，某个选择器才会出现。如果 DOCX 没有样式目录（或所有命名样式都不在这 16 个选择器映射中），`cssStyles` 将为 `{}`。

### 自定义节点与标记映射

您可以通过请求体中的 `prosemirrorNodes` 和 `prosemirrorMarks` 覆盖导入时的默认 `node/mark` 类型。如果您的编辑器使用自定义的 `nodes/marks`，希望导入的 `JSON` 采用它们，则需要提供这些映射。

例如，如果您的 schema 使用名为 `textBlock` 的自定义节点替代默认的段落，可以在请求体中包含 `"{\"textBlock\":\"paragraph\"}"`。

您也可以类似地调整标题、列表、加粗或斜体等标记。

#### 默认节点

| Name                | Description                 |
| ------------------- | --------------------------- |
| `paragraph`         | 定义用于段落转换的 ProseMirror 类型    |
| `heading`           | 定义用于标题转换的 ProseMirror 类型    |
| `blockquote`        | 定义用于引用块转换的 ProseMirror 类型   |
| `codeblock`         | 定义用于代码块转换的 ProseMirror 类型   |
| `bulletlist`        | 定义用于无序列表转换的 ProseMirror 类型  |
| `orderedlist`       | 定义用于有序列表转换的 ProseMirror 类型  |
| `listitem`          | 定义用于列表项转换的 ProseMirror 类型   |
| `hardbreak`         | 定义用于硬换行转换的 ProseMirror 类型   |
| `horizontalrule`    | 定义用于水平分割线转换的 ProseMirror 类型 |
| `table`             | 定义用于表格转换的 ProseMirror 类型    |
| `tablecell`         | 定义用于表格单元格转换的 ProseMirror 类型 |
| `tableheader`       | 定义用于表头转换的 ProseMirror 类型    |
| `tablerow`          | 定义用于表格行转换的 ProseMirror 类型   |
| `image`             | 定义用于图片转换的 ProseMirror 标记    |
| `footnoteReference` | 定义用于脚注引用转换的 ProseMirror 类型  |
| `endnoteReference`  | 定义用于尾注引用转换的 ProseMirror 类型  |

#### 默认标记

| Name            | Description               |
| --------------- | ------------------------- |
| `bold`          | 定义用于加粗转换的 ProseMirror 标记  |
| `italic`        | 定义用于斜体转换的 ProseMirror 标记  |
| `underline`     | 定义用于下划线转换的 ProseMirror 标记 |
| `strikethrough` | 定义用于删除线转换的 ProseMirror 标记 |
| `link`          | 定义用于链接转换的 ProseMirror 标记  |
| `code`          | 定义用于代码转换的 ProseMirror 标记  |

## 支持与限制

有关管道每个阶段支持哪些文档特性的详细说明，请参见 [支持的特性](https://tiptap.zhcndoc.com/conversion/getting-started/feature-support-matrix.md) 矩阵。
