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

# 通过 REST API 导出 DOCX

了解如何通过 Conversion REST API 将 Tiptap JSON 文档导出为 DOCX 格式。

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

  在您的账户中开始 [免费试用](https://cloud.tiptap.dev/v2?trial=true) 或 [订阅 Start
  套餐](https://cloud.tiptap.dev/v2/billing)。
- **2. Configure Convert app**

  Authenticate REST calls with a signed token carrying `aud: "Convert"`. See [Authentication](https://tiptap.zhcndoc.com/authentication.md).

DOCX 导出 API 会将 Tiptap JSON 文档转换为 `.docx`（Microsoft Word）文件。它使用与 [编辑器扩展](https://tiptap.zhcndoc.com/conversion/export/docx/editor-extension.md) 相同的转换库，并为标准内容生成等效的 DOCX 输出。

The REST API supports [style overrides](https://tiptap.zhcndoc.com/conversion/export/docx/styles.md), [custom-node rendering via the DSL](https://tiptap.zhcndoc.com/conversion/export/docx/custom-nodes-dsl.md), page size and margins, headers/footers, comment threads, and element-level overrides (`tableOverrides`, `paragraphOverrides`, `textRunOverrides`, `tableCellOverrides`, `imageOverrides`). It does not accept JavaScript-function options. For the function-based custom-node API, use the [editor extension](https://tiptap.zhcndoc.com/conversion/export/docx/editor-extension.md), which also works server-side.

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

## 导出 DOCX

`POST /v2/convert/export/docx`

`/v2/convert/export/docx` 端点将 Tiptap 文档转换为 `DOCX` 格式。用户可以向此端点 `POST` 文档，并使用多种参数自定义转换过程中不同文档元素的处理方式。

> **支持导出自定义:**
>
> `/v2/convert/export/docx` 端点接受 [样式覆盖](https://tiptap.zhcndoc.com/conversion/export/docx/styles.md)、页面大小/页边距、页眉/页脚、五种元素级覆盖（`tableOverrides`、
> `paragraphOverrides`、`textRunOverrides`、`tableCellOverrides`、`imageOverrides`），以及 [通过 JSON DSL 的自定义节点渲染](https://tiptap.zhcndoc.com/conversion/export/docx/custom-nodes-dsl.md)。它不
> 接受 JavaScript 函数选项。对于基于函数的自定义节点 API，请使用 [编辑器
> 扩展](https://tiptap.zhcndoc.com/conversion/export/docx/editor-extension.md) 或 [服务端导出
> 指南](https://tiptap.zhcndoc.com/conversion/export/docx/editor-extension.md#server-side-export)。

### 示例（cURL）

```bash
curl --output example.docx -X POST "https://api.tiptap.dev/v2/convert/export/docx" \
    -H "Authorization: Bearer YOUR_TOKEN" \
    -H "Content-Type: application/json" \
    -d '{
      "doc": "{\"type\":\"doc\",\"content\":[{\"type\":\"paragraph\",\"attrs\":{\"textAlign\":\"left\"},\"content\":[{\"type\":\"text\",\"text\":\"欢迎参加本次演示，展示我们的编辑器如何将各种格式选项导出为 DOCX，确保您的内容在 Word 中保持预期外观。\"}]}]}",
      "exportType": "blob"
    }'
```

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

### 必填请求头

| Name            | Description                                                                 |
| --------------- | --------------------------------------------------------------------------- |
| `Authorization` | The JWT token to authenticate the request. Example: `Bearer your-jwt-token` |
| `Content-Type`  | Must be `application/json`                                                  |

### 请求体

| Name                 | Type              | Description                                                                                                                                                                                                                                                                                                                                                                  | Default     |
| -------------------- | ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------- |
| `doc`                | `String`          | Tiptap's JSON                                                                                                                                                                                                                                                                                                                                                                | `N/A`       |
| `exportType`         | `string`          | The expected export type                                                                                                                                                                                                                                                                                                                                                     | `blob`      |
| `styleOverrides`     | `Object`          | Style overrides                                                                                                                                                                                                                                                                                                                                                              | `{}`        |
| `pageSize`           | `Object`          | Page size configuration                                                                                                                                                                                                                                                                                                                                                      | `undefined` |
| `pageMargins`        | `Object`          | Page margins configuration                                                                                                                                                                                                                                                                                                                                                   | `undefined` |
| `headers`            | `Object`          | Page header configuration                                                                                                                                                                                                                                                                                                                                                    | `undefined` |
| `footers`            | `Object`          | Page footer configuration                                                                                                                                                                                                                                                                                                                                                    | `undefined` |
| `tableOverrides`     | `Object`          | Table-level rendering overrides                                                                                                                                                                                                                                                                                                                                              | `undefined` |
| `paragraphOverrides` | `Object`          | Paragraph-level rendering overrides                                                                                                                                                                                                                                                                                                                                          | `undefined` |
| `textRunOverrides`   | `Object`          | Text run rendering overrides                                                                                                                                                                                                                                                                                                                                                 | `undefined` |
| `tableCellOverrides` | `Object`          | Table cell rendering overrides                                                                                                                                                                                                                                                                                                                                               | `undefined` |
| `imageOverrides`     | `Object`          | Image rendering overrides                                                                                                                                                                                                                                                                                                                                                    | `undefined` |
| `customNodeDsl`      | `Object`          | [Custom-node DSL](https://tiptap.zhcndoc.com/conversion/export/docx/custom-nodes-dsl.md) rules                                                                                                                                                                                                                                                                               | `undefined` |
| `placeholders`       | `Object \| false` | Optional `{ page?, total? }` rename map matching `Pages.configure({ placeholders })` so renamed tokens (e.g. `{p}` / `{pages}`) in plain-text headers/footers become live `PAGE` / `NUMPAGES` fields. Pass `false` to disable substitution entirely (literal `{page}` / `{total}` text in the exported `.docx`). See [Custom token names](#custom-token-names-placeholders). | `undefined` |
| `comments`           | `Object`          | Comment threads to embed as native Word comments: `{ threads: [...] }`. Each thread carries its messages, author, dates, and resolved state, and is anchored to the document's `inlineThread` / `blockThread` marks. See [Comments](#comments).                                                                                                                              | `undefined` |

#### 页面尺寸配置

`pageSize` 对象允许您自定义导出 DOCX 文档的页面尺寸：

| Property | Type     | Description                              | Default    |
| -------- | -------- | ---------------------------------------- | ---------- |
| `width`  | `string` | 页面的宽度。必须是一个正数，后跟有效单位（cm、in、pt、pc、mm、px）。 | `"21.0cm"` |
| `height` | `string` | 页面的高度。必须是一个正数，后跟有效单位（cm、in、pt、pc、mm、px）。 | `"29.7cm"` |

**带自定义页面尺寸的 cURL 示例：**

```bash
curl --output example.docx -X POST "https://api.tiptap.dev/v2/convert/export/docx" \
    -H "Authorization: Bearer YOUR_TOKEN" \
    -H "Content-Type: application/json" \
    -d '{
      "doc": "{\"type\":\"doc\",\"content\":[{\"type\":\"paragraph\",\"content\":[{\"type\":\"text\",\"text\":\"自定义页面尺寸的文档\"}]}]}",
      "exportType": "blob",
      "pageSize": {"width": "21.0cm", "height": "29.7cm"}
    }'
```

#### 页面边距配置

`pageMargins` 对象允许您自定义导出 DOCX 文档的页面边距：

| Property | Type     | Description                                     | Default   |
| -------- | -------- | ----------------------------------------------- | --------- |
| `top`    | `string` | 页面的上边距。可以为负数。必须是一个数字，后跟有效单位（cm、in、pt、pc、mm、px）。 | `"1.0cm"` |
| `bottom` | `string` | 页面的下边距。可以为负数。必须是一个数字，后跟有效单位（cm、in、pt、pc、mm、px）。 | `"1.0cm"` |
| `left`   | `string` | 页面的左边距。必须是一个正数，后跟有效单位（cm、in、pt、pc、mm、px）。       | `"1.0cm"` |
| `right`  | `string` | 页面的右边距。必须是一个正数，后跟有效单位（cm、in、pt、pc、mm、px）。       | `"1.0cm"` |

**带自定义页面边距的 cURL 示例：**

```bash
curl --output example.docx -X POST "https://api.tiptap.dev/v2/convert/export/docx" \
    -H "Authorization: Bearer YOUR_TOKEN" \
    -H "Content-Type: application/json" \
    -d '{
      "doc": "{\"type\":\"doc\",\"content\":[{\"type\":\"paragraph\",\"content\":[{\"type\":\"text\",\"text\":\"自定义边距的文档\"}]}]}",
      "exportType": "blob",
      "pageMargins": {"top": "2.0cm", "bottom": "2.0cm", "left": "1.5cm", "right": "1.5cm"}
    }'
```

#### 页眉和页脚

`headers` 和 `footers` 对象允许您自定义导出 DOCX 的一系列页眉和页脚选项。

##### 页眉配置

`headers` 对象允许您自定义导出 DOCX 文档的页眉：

| Property             | Type      | Description                                                                                 |
| -------------------- | --------- | ------------------------------------------------------------------------------------------- |
| `evenAndOddHeaders`  | `boolean` | 是否为奇数页和偶数页使用不同的页眉                                                                           |
| `differentFirstPage` | `boolean` | 是否在首页使用不同的页眉。设为 `true` 时，首页使用 `first` 值而不是 `default`。                                       |
| `default`            | `string`  | 每一页的标准默认页眉；当启用 `evenAndOddHeaders` 选项时，则为奇数页页眉。可接受纯文本字符串或字符串化的 Tiptap JSONContent 以实现富文本格式。 |
| `first`              | `string`  | 首页页眉。仅当 `differentFirstPage` 设为 `true` 时使用。可接受纯文本字符串或字符串化的 Tiptap JSONContent 以实现富文本格式。     |
| `even`               | `string`  | 启用 `evenAndOddHeaders` 选项时的偶数页页眉。可接受纯文本字符串或字符串化的 Tiptap JSONContent 以实现富文本格式。               |

> **纯文本 vs. Tiptap JSONContent:**
>
> 每个页眉值都可以是 **纯文本字符串**（生成简单、无样式的页眉）或 **字符串化的 Tiptap JSONContent** 对象（可启用加粗、斜体、链接等富文本格式）。当传入 JSONContent 时，请在请求体中发送前使用 `JSON.stringify()` 将对象转为字符串。

**带自定义页眉的 cURL 示例：**

```bash
curl --output example.docx -X POST "https://api.tiptap.dev/v2/convert/export/docx" \
    -H "Authorization: Bearer YOUR_TOKEN" \
    -H "Content-Type: application/json" \
    -d '{
      "doc": "{\"type\":\"doc\",\"content\":[{\"type\":\"paragraph\",\"content\":[{\"type\":\"text\",\"text\":\"带自定义页眉的文档\"}]}]}",
      "exportType": "blob",
      "headers": {"evenAndOddHeaders": true, "default": "默认页眉", "first": "首页页眉", "even": "偶数页页眉"}
    }'
```

#### 页脚配置

`footers` 对象允许您自定义导出 DOCX 文档的页脚：

| Property             | Type      | Description                                                                                 |
| -------------------- | --------- | ------------------------------------------------------------------------------------------- |
| `evenAndOddFooters`  | `boolean` | 是否为奇数页和偶数页使用不同的页脚                                                                           |
| `differentFirstPage` | `boolean` | 是否在首页使用不同的页脚。设为 `true` 时，首页使用 `first` 值而不是 `default`。                                       |
| `default`            | `string`  | 每一页的标准默认页脚；当启用 `evenAndOddFooters` 选项时，则为奇数页页脚。可接受纯文本字符串或字符串化的 Tiptap JSONContent 以实现富文本格式。 |
| `first`              | `string`  | 首页页脚。仅当 `differentFirstPage` 设为 `true` 时使用。可接受纯文本字符串或字符串化的 Tiptap JSONContent 以实现富文本格式。     |
| `even`               | `string`  | 启用 `evenAndOddFooters` 选项时的偶数页页脚。可接受纯文本字符串或字符串化的 Tiptap JSONContent 以实现富文本格式。               |

> **纯文本 vs. Tiptap JSONContent:**
>
> 每个页脚值都可以是 **纯文本字符串**（生成简单、无样式的页脚）或 **字符串化的 Tiptap JSONContent** 对象（可启用加粗、斜体、链接等富文本格式）。当传入 JSONContent 时，请在请求体中发送前使用 `JSON.stringify()` 将对象转为字符串。

> **\`\{page}\` / \`\{total}\` tokens become live Word fields:**
>
> The REST API translates `{page}`, `{total}`, and the `{numpages}` synonym inside plain-text
> headers/footers into live Word `PAGE` / `NUMPAGES` fields in the exported `.docx`. Custom token
> names (e.g. `{p}` / `{pages}`) require passing the optional `placeholders` rename map. See [Custom
> token names](#custom-token-names-placeholders) below. Pass `"placeholders": false` to ship the
> tokens as literal text instead.

#### 自定义标记名称 (`placeholders`)

当编辑器通过 [`Pages.configure({ placeholders })`](https://tiptap.zhcndoc.com/pages/core-concepts/page-header-footer.md#renaming-or-disabling-placeholders) 重命名内置标记时，请将同样的重命名映射传给 REST API，以保持传输格式一致。该字段在传输层中的名称和结构与编辑器选项相同：

```json
{
  "doc": "{\"type\":\"doc\",\"content\":[]}",
  "footers": { "default": "{p} of {pages}" },
  "placeholders": { "page": "p", "total": "pages" }
}
```

When the map is omitted, the service falls back to recognizing `{page}`, `{total}`, and `{numpages}` (Word's spelling for the total-pages field, kept as a synonym so direct REST API callers can mirror what `/import/docx` emits). Renaming `total` removes the `{numpages}` synonym so stale tokens render literally; the rename is strict. Pass `"placeholders": false` to disable substitution on every slot so all `{page}` / `{total}` text ships literally with no live fields.

**带自定义页脚的 cURL 示例：**

```bash
curl --output example.docx -X POST "https://api.tiptap.dev/v2/convert/export/docx" \
    -H "Authorization: Bearer YOUR_TOKEN" \
    -H "Content-Type: application/json" \
    -d '{
      "doc": "{\"type\":\"doc\",\"content\":[{\"type\":\"paragraph\",\"content\":[{\"type\":\"text\",\"text\":\"Document with custom footers\"}]}]}",
      "exportType": "blob",
      "footers": {"evenAndOddFooters": true, "default": "Default Footer", "first": "First Page Footer", "even": "Even Page Footer"}
    }'
```

### Comments

Pass a `comments` object to embed comment threads as native Word comments in the exported `.docx`. Each thread is anchored to the text it belongs to through the document's own comment markers: an `inlineThread` mark whose `data-thread-id` matches the thread `id`, or a `blockThread` node. The `comments` field supplies the thread bodies, authors, dates, and resolved state.

The shape mirrors the editor's export extension:

| Field                  | Type               | Description                                                                                                                    |
| ---------------------- | ------------------ | ------------------------------------------------------------------------------------------------------------------------------ |
| `threads`              | `Array`            | The comment threads to embed.                                                                                                  |
| `threads[].id`         | `String`           | Thread id. Must match the `data-thread-id` on the matching `inlineThread` / `blockThread` in `doc`.                            |
| `threads[].resolvedAt` | `String \| null`   | When set, the thread is exported as resolved.                                                                                  |
| `threads[].comments`   | `Array`            | The thread's messages, root first, then replies in order.                                                                      |
| `comments[].id`        | `String`           | Message id.                                                                                                                    |
| `comments[].content`   | `String \| Object` | The message body as plain text or Tiptap JSON.                                                                                 |
| `comments[].data`      | `Object`           | Optional metadata: `author`, `initials`, `dateIso`, `dateUtc`, and round-trip identities (`originalWId`, `originalDurableId`). |

When omitted, the export contains no comments, so existing requests are unaffected.

**Example cURL with a comment thread:**

```bash
curl --output example.docx -X POST "https://api.tiptap.dev/v2/convert/export/docx" \
    -H "Authorization: Bearer YOUR_TOKEN" \
    -H "X-App-Id: YOUR_APP_ID" \
    -H "Content-Type: application/json" \
    -d '{
      "doc": "{\"type\":\"doc\",\"content\":[{\"type\":\"paragraph\",\"content\":[{\"type\":\"text\",\"text\":\"Reviewed text\",\"marks\":[{\"type\":\"inlineThread\",\"attrs\":{\"data-thread-id\":\"T1\"}}]}]}]}",
      "exportType": "blob",
      "comments": {
        "threads": [
          {
            "id": "T1",
            "resolvedAt": null,
            "comments": [
              {
                "id": "c1",
                "content": "Please cite a source.",
                "data": { "author": "Ada Lovelace", "initials": "AL", "dateIso": "2026-01-01T00:00:00.000Z" }
              }
            ]
          }
        ]
      }
    }'
```

### 元素覆盖

#### 组合多个元素覆盖的示例 cURL

```bash
curl --output example.docx -X POST "https://api.tiptap.dev/v2/convert/export/docx" \
    -H "Authorization: Bearer YOUR_TOKEN" \
    -H "Content-Type: application/json" \
    -d '{
      "doc": "{\"type\":\"doc\",\"content\":[{\"type\":\"paragraph\",\"content\":[{\"type\":\"text\",\"text\":\"带元素级覆盖的文档\"}]}]}",
      "tableOverrides": {
        "borders": {
          "top": { "style": "none" },
          "bottom": { "style": "none" },
          "left": { "style": "none" },
          "right": { "style": "none" },
          "insideHorizontal": { "style": "none" },
          "insideVertical": { "style": "none" }
        }
      },
      "paragraphOverrides": {
        "spacing": { "before": 200, "after": 200 }
      },
      "textRunOverrides": {
        "font": "Arial",
        "size": 24
      },
      "tableCellOverrides": {
        "shading": { "fill": "F0F0F0", "type": "clear" },
        "verticalAlign": "center"
      },
      "imageOverrides": {
        "transformation": { "width": 400, "height": 300 }
      }
    }'
```

### 响应

成功时，API 以二进制形式返回 DOCX 文件下载：

- **状态**: `200 OK`
- **Content-Type**: `application/vnd.openxmlformats-officedocument.wordprocessingml.document`
- **Content-Disposition**: `attachment; filename=export-{timestamp}.docx`

### 错误响应

| Status | Code                             | Description  |
| ------ | -------------------------------- | ------------ |
| 400    | `NO_DOCUMENT_PROVIDED`           | 未在请求体中提供文档   |
| 422    | `FAILED_TO_PARSE_DOCX_FILE`      | 解析 JSON 输入失败 |
| 422    | `FAILED_TO_EXPORT_DOCX_FILE`     | 导出 DOCX 失败   |
| 422    | `FAILED_TO_CONVERT_DOCX_TO_BLOB` | 转换结果类型失败     |

## 转换字体

`POST /v2/convert/fonts/convert`

将字体转换为可嵌入 DOCX 文件的形式：`TTF` / `OTF` 上传会原样返回，而 `WOFF2` 上传会转换为 `TTF`。这是编辑器扩展的 [`embedFonts`](https://tiptap.zhcndoc.com/conversion/export/docx/fonts.md#automatic-embedding) 选项在后台调用的端点；你也可以直接调用它。自 Convert Service **v2.25.0** 起可用。

> The endpoint is stateless: nothing is stored. Each request is converted and the temporary files
> are cleaned up immediately.

### 必需请求头

```bash
Authorization: Bearer <your-jwt>
```

### 请求体

`multipart/form-data`:

| 字段           | 类型       | 描述                                      | 必填 |
| ------------ | -------- | --------------------------------------- | -- |
| `file`       | `File`   | 字体二进制文件（`TTF`、`OTF` 或 `WOFF2`）。最大 25MB。 | 是  |
| `fontFamily` | `String` | 字体族名称，仅用于日志记录。                          | 否  |

### 示例（cURL）

```bash
curl --output MyFont.ttf -X POST "https://api.tiptap.dev/v2/convert/fonts/convert" \
  -H "Authorization: Bearer <your-jwt>" \
  -F "file=@MyFont.woff2" \
  -F "fontFamily=My Font"
```

### 响应

成功时，API 会将可嵌入的字体作为二进制下载返回：

- **状态**：`200 OK`
- **Content-Type**: `font/ttf`

### 错误响应

| Status | Code                      | Description                                            |
| ------ | ------------------------- | ------------------------------------------------------ |
| 400    | None                      | Request validation error (e.g. no `file` field)        |
| 413    | `FONT_FILE_TOO_LARGE`     | The uploaded font exceeds the 25MB limit               |
| 422    | `UNSUPPORTED_FONT_FORMAT` | The upload is not a recognized TTF, OTF, or WOFF2 font |
| 422    | `FONT_CONVERSION_FAILED`  | The WOFF2 → TTF conversion produced no output          |
| 500    | `FONT_CONVERSION_FAILED`  | Unexpected error during conversion                     |
