---
title: "从你的编辑器导出 EPUB"
description: "了解如何在我们的文档中使用“导出 EPUB”扩展将 Tiptap 编辑器内容导出为 EPUB 文件。"
canonical_url: "https://tiptap.zhcndoc.com/conversion/export/epub/editor-extension"
---

# 从你的编辑器导出 EPUB

了解如何在我们的文档中使用“导出 EPUB”扩展将 Tiptap 编辑器内容导出为 EPUB 文件。

- **1. 开通试用或订阅**

  在你的账户中开始 [免费试用](https://cloud.tiptap.dev/v2?trial=true) 或 [订阅 Start 方案](https://cloud.tiptap.dev/v2/billing)。
- **2. 从私有注册表安装**

  要安装这些前端扩展，请按照 [安装指南](https://tiptap.zhcndoc.com/guides/pro-extensions.md) 通过验证以访问 Tiptap 的私有 npm 注册表。

> **Interactive demo:** [ExportEpub](https://embed-pro.tiptap.dev/preview/Extensions/ExportEpub)

使用 Tiptap 的 `@tiptap-pro/extension-export-epub` 可将编辑器内容导出为 `.epub` 文件。该扩展通过将文档发送到 Tiptap convert 服务进行转换，为你的编辑器集成 EPUB 导出功能。

如果你更希望自行处理转换，也可以改用 [REST API](https://tiptap.zhcndoc.com/conversion/export/epub/rest-api.md)。

## 安装 EPUB 导出扩展

Conversion 扩展发布在 Tiptap 的私有 npm 注册表中。请按照 [私有注册表指南](https://tiptap.zhcndoc.com/guides/pro-extensions.md) 集成这些扩展。

完成后，你就可以安装并导入 **导出 EPUB** 扩展包。

```bash
npm i @tiptap-pro/extension-export-epub
```

```js
import { ExportEpub } from '@tiptap-pro/extension-export-epub'
```

## 配置扩展

`ExportEpub` 扩展可通过 `configure` 方法接收一个 `ExportEpubOptions`（`object`）作为参数，并支持以下属性：

```ts
import { ExportEpub } from '@tiptap-pro/extension-export-epub'

const editor = new Editor({
  extensions: [
    // 其他扩展 ...
    ExportEpub.configure({
      endpoint: 'https://api.tiptap.dev/v2/convert',
      token: 'YOUR_TOKEN',
      styleOverrides: {},
      headers: {},
      footers: {},
      pageSize: { width: '21cm', height: '29.7cm' },
      pageMargins: { top: '1cm', bottom: '1cm', left: '1cm', right: '1cm' },
      customNodes: [],
      onCompleteExport: (result) => {
        // 处理导出的 Blob
      },
    }),
    // 其他扩展 ...
  ],
})
```

| 参数                 | 类型                       | 描述                                                         | 默认值                                   |
| ------------------ | ------------------------ | ---------------------------------------------------------- | ------------------------------------- |
| `endpoint`         | `string`                 | 用于转换的 Tiptap API 端点                                        | `'https://api.tiptap.dev/v2/convert'` |
| `token`            | `string`                 | 用于身份验证的 Tiptap JWT                                         | `''`                                  |
| `styleOverrides`   | `Record<string, string>` | 要应用于导出的样式覆盖                                                | `undefined`                           |
| `headers`          | `HeaderConfig`           | 导出文档的页眉配置                                                  | `undefined`                           |
| `footers`          | `FooterConfig`           | 导出文档的页脚配置                                                  | `undefined`                           |
| `pageSize`         | `PageSize`               | 页面尺寸配置                                                     | `undefined`                           |
| `pageMargins`      | `PageMargins`            | 页面边距配置                                                     | `undefined`                           |
| `customNodes`      | `CustomNodeDefinition[]` | 基于 DOCX 转换的自定义节点定义（需要 `@tiptap-pro/extension-export-docx`） | `undefined`                           |
| `onCompleteExport` | `(result: Blob) => void` | 接收导出文件 Blob 的回调                                            | 如果未提供则抛出错误                            |

### HeaderConfig

| 属性                   | 类型        | 描述                                                                                       |
| -------------------- | --------- | ---------------------------------------------------------------------------------------- |
| `evenAndOddHeaders`  | `boolean` | 是否为奇数页和偶数页使用不同的页眉                                                                        |
| `differentFirstPage` | `boolean` | 是否在首页使用不同的页眉。设置为 `true` 时，第一页将使用 `first` 的值而不是 `default`。                                |
| `default`            | `string`  | 每页的标准默认页眉，或在启用 `evenAndOddHeaders` 时奇数页的页眉。可接受纯文本字符串或字符串化的 Tiptap JSONContent，用于富文本格式。   |
| `first`              | `string`  | 首页的页眉。仅在 `differentFirstPage` 设置为 `true` 时使用。可接受纯文本字符串或字符串化的 Tiptap JSONContent，用于富文本格式。 |
| `even`               | `string`  | 启用 `evenAndOddHeaders` 选项时偶数页的页眉。可接受纯文本字符串或字符串化的 Tiptap JSONContent，用于富文本格式。             |

### FooterConfig

| 属性                   | 类型        | 描述                                                                                       |
| -------------------- | --------- | ---------------------------------------------------------------------------------------- |
| `evenAndOddFooters`  | `boolean` | 是否为奇数页和偶数页使用不同的页脚                                                                        |
| `differentFirstPage` | `boolean` | 是否在首页使用不同的页脚。设置为 `true` 时，第一页将使用 `first` 的值而不是 `default`。                                |
| `default`            | `string`  | 每页的标准默认页脚，或在启用 `evenAndOddFooters` 时奇数页的页脚。可接受纯文本字符串或字符串化的 Tiptap JSONContent，用于富文本格式。   |
| `first`              | `string`  | 首页的页脚。仅在 `differentFirstPage` 设置为 `true` 时使用。可接受纯文本字符串或字符串化的 Tiptap JSONContent，用于富文本格式。 |
| `even`               | `string`  | 启用 `evenAndOddFooters` 选项时偶数页的页脚。可接受纯文本字符串或字符串化的 Tiptap JSONContent，用于富文本格式。             |

### PageSize

| 属性       | 类型       | 描述                                      | 默认值        |
| -------- | -------- | --------------------------------------- | ---------- |
| `width`  | `string` | 页面宽度。必须是一个正数，后跟有效单位（cm、in、pt、pc、mm、px）。 | `"21cm"`   |
| `height` | `string` | 页面高度。必须是一个正数，后跟有效单位（cm、in、pt、pc、mm、px）。 | `"29.7cm"` |

### PageMargins

| 属性       | 类型       | 描述                                              | 默认值     |
| -------- | -------- | ----------------------------------------------- | ------- |
| `top`    | `string` | 页面的上边距。可以为负数。必须是一个数字，后跟有效单位（cm、in、pt、pc、mm、px）。 | `"1cm"` |
| `bottom` | `string` | 页面的下边距。可以为负数。必须是一个数字，后跟有效单位（cm、in、pt、pc、mm、px）。 | `"1cm"` |
| `left`   | `string` | 页面的左边距。必须是一个正数，后跟有效单位（cm、in、pt、pc、mm、px）。       | `"1cm"` |
| `right`  | `string` | 页面的右边距。必须是一个正数，后跟有效单位（cm、in、pt、pc、mm、px）。       | `"1cm"` |

## 导出 EPUB 文件

安装扩展后，你可以使用 `exportEpub` 命令将编辑器内容导出为 `.epub`。

```ts
/**
 * 通过 Tiptap convert 服务将当前文档导出为 EPUB 文件。
 *
 * @param options - 所有扩展级选项都可以在单次调用中覆盖
 * @example editor.commands.exportEpub({ onCompleteExport: (result) => {} })
 */
exportEpub: (options?: ExportEpubCommandOptions) => ReturnType
```

`ExportEpubCommandOptions` 接口扩展了 `ExportEpubOptions`，因此每个配置项都可以在单次命令调用中被覆盖：

| Property           | Type                     | Description     |
| ------------------ | ------------------------ | --------------- |
| `endpoint`         | `string`                 | 覆盖此特定导出的 API 端点 |
| `token`            | `string`                 | 覆盖此特定导出的 JWT 令牌 |
| `styleOverrides`   | `Record<string, string>` | 覆盖此特定导出的样式覆盖    |
| `headers`          | `HeaderConfig`           | 覆盖此特定导出的页眉配置    |
| `footers`          | `FooterConfig`           | 覆盖此特定导出的页脚配置    |
| `pageSize`         | `PageSize`               | 覆盖此特定导出的页面尺寸    |
| `pageMargins`      | `PageMargins`            | 覆盖此特定导出的页边距     |
| `customNodes`      | `CustomNodeDefinition[]` | 覆盖此特定导出的自定义节点定义 |
| `onCompleteExport` | `(result: Blob) => void` | 覆盖此特定导出的回调      |

```js
import { ExportEpub } from '@tiptap-pro/extension-export-epub'

const editor = new Editor({
  extensions: [
    // 其他扩展 ...
    ExportEpub.configure({
      token: 'YOUR_TOKEN',
      onCompleteExport(result) {
        // 下载 EPUB 文件
        const url = URL.createObjectURL(result)
        const a = document.createElement('a')

        a.href = url
        a.download = 'document.epub'
        a.click()

        URL.revokeObjectURL(url)
      },
    }),
    // 其他扩展 ...
  ],
})

// 使用扩展级回调
editor.chain().exportEpub().run()

// 或为特定导出覆盖选项
editor
  .chain()
  .exportEpub({
    pageSize: { width: '8.5in', height: '11in' },
    onCompleteExport(result) {
      // 此特定导出的自定义处理
      const url = URL.createObjectURL(result)
      window.open(url)
    },
  })
  .run()
```

### 工作原理

当你调用 `exportEpub` 时，扩展会将编辑器的文档和任何已配置的选项（样式覆盖、页面布局、页眉、页脚）发送到 Convert 服务，Convert 服务会返回生成的 `.epub` 文件，形式为二进制 blob。`onCompleteExport` 回调会直接接收该 blob。错误会以异常形式抛出，而不是通过回调传递。

## 预期内容

- **需要身份验证**（`token` JWT）。在服务端生成 JWT。请参阅 [Conversion 安装指南](https://tiptap.zhcndoc.com/conversion/getting-started/install.md)。
- **需要处理的 HTTP 响应：**`401`（缺少或无效的 JWT）、`403`（你的应用不允许执行该操作——通常是你的套餐不包含的格式）、`5xx`（临时性服务端错误；请使用退避重试）。
- \*\*每个请求都会在响应前端到端处理完毕。\*\*对于长文档，请预留更长的往返时间。

## 不应期待的内容

- **按章节的元数据自定义。** EPUB 元数据（书名、作者、语言、自定义章节 spine）目前还不能通过导出选项进行配置。
- **在不同阅读应用中达到像素级一致的渲染。** EPUB 渲染取决于阅读应用；不同应用和设备之间的间距、字体回退和图像缩放会有所差异。请针对你的受众所使用的阅读器进行测试。

## 支持与限制

| **功能**              | **支持情况**                   |
| ------------------- | -------------------------- |
| **文本内容**            | ✓ 基本文本、间距、标点符号             |
| **文本格式**            | ✓ 粗体、斜体、下划线、删除线、对齐方式、行高    |
| **块级元素**            | ✓ 段落、标题（1–6）、引用块、有序列表和无序列表 |
| **表格**              | ✓ 基本结构、表头行、跨列合并            |
| **链接**              | ✓ 超链接                      |
| **媒体（图片）**          | ✓ 嵌入图片，保留尺寸                |
| **样式**              | ✓ 字体族\*、字体颜色、字体大小、背景颜色、行高  |
| **页眉与页脚**           | ✓                          |
| **数学公式**            | ✓                          |
| **分页符**             | ✓                          |
| **章节**              | ✗                          |
| **脚注与尾注**           | ✗                          |
| **批注与修订**           | ✗                          |
| **目录**              | ✗                          |
| **高级格式**            | ✗ 分栏、文字方向、表单、宏、嵌入脚本        |
| **元数据**             | ✗                          |
| **文本框、形状、SmartArt** | ✗                          |

- 只要在导出文件打开时，目标字体已安装在操作系统上，就支持字体族。

如需按功能查看详细说明，请参阅 [支持的功能](https://tiptap.zhcndoc.com/conversion/getting-started/feature-support-matrix.md) 矩阵。请注意，[DOCX 导出扩展](https://tiptap.zhcndoc.com/conversion/export/docx/editor-extension.md) 中可用的元素覆盖（`paragraphOverrides`、`textRunOverrides`、`tableOverrides`、`tableCellOverrides`、`imageOverrides`）不会传递到 EPUB 转换中。
