文档
导出为 Docx

导出区块为 docx

可以完全在客户端将 BlockNote 文档导出为 Docx。

此功能由 @blocknote/xl-docx-exporter 提供。xl- 系列包是完全开源的,但采用了 copyleft 许可证。 在闭源专有产品中使用需购买 商务订阅 中包含的商业许可证。

首先,安装 @blocknote/xl-docx-exporterdocx 包:

npm install @blocknote/xl-docx-exporter docx

然后,创建 DOCXExporter 类的实例。它提供以下方法:

import {
  DOCXExporter,
  docxDefaultSchemaMappings,
} from "@blocknote/xl-docx-exporter";
import { Packer } from "docx";
 
// 创建导出器
const exporter = new DOCXExporter(editor.schema, docxDefaultSchemaMappings);
 
// 将区块转换为 docxjs 文档
const docxDocument = await exporter.toDocxJsDocument(editor.document);
 
// 使用 docx 写入文件:
await Packer.toBuffer(docxDocument);

请参阅下面的完整示例

Pro Example

Get access to the full source code for pro examples by subscribing to BlockNote Pro

Or sign in

自定义 Docx 输出文件

toDocxJsDocument 接受一个可选的 options 参数,允许你自定义文档元数据(比如作者)和节选项(比如页眉和页脚)。

示例用法:

import { Paragraph, TextRun } from "docx";
 
const doc = await exporter.toDocxJsDocument(testDocument, {
  documentOptions: {
    creator: "John Doe",
  },
  sectionOptions: {
    headers: {
      default: {
        options: {
          children: [new Paragraph({ children: [new TextRun("Header")] })],
        },
      },
    },
    footers: {
      default: {
        options: {
          children: [new Paragraph({ children: [new TextRun("Footer")] })],
        },
      },
    },
  },
});

自定义映射 / 自定义模式

DOCXExporter 构造函数接收 schemamappingsoptions 参数。 mapping 定义了如何将 BlockNote 的模式元素(区块、行内内容或样式)转换为 docxjs (opens in a new tab) 元素。 如果你在编辑器中使用了自定义模式,或者想覆盖默认 BlockNote 元素如何转换为 docx,可以传入你自己的 mappings

例如,若你的模式包含一个 extraBlock 类型,可以用如下代码:

import {
  DOCXExporter,
  docxDefaultSchemaMappings,
} from "@blocknote/xl-docx-exporter";
import { Paragraph, TextRun } from "docx";
 
new DOCXExporter(schema, {
  blockMapping: {
    ...docxDefaultSchemaMappings.blockMapping,
    myCustomBlock: (block, exporter) => {
      return new Paragraph({
        children: [
          new TextRun({
            text: "My custom block",
          }),
        ],
      });
    },
  },
  inlineContentMapping: docxDefaultSchemaMappings.inlineContentMapping,
  styleMapping: docxDefaultSchemaMappings.styleMapping,
});

导出器选项

DOCXExporter 构造函数接受一个可选的 options 参数。 虽然转换在客户端进行,默认配置使用一个服务器端代理来解析文件:

const defaultOptions = {
  // 用于解析外部资源以避免 CORS 问题的函数
  // 默认情况下,这会调用 BlockNote 托管的服务器端代理来解析文件
  resolveFileUrl: corsProxyResolveFileUrl,
  // Docx 中用于高亮、背景色和字体颜色的颜色配置
  colors: COLORS_DEFAULT, // 来自 @blocknote/core 的默认值
};