WangEditor5-将内容转为Word并下载

WangEditor5-将内容转为Word并下载

wangEditor官网https://www.wangeditor.com/v5/toolbar-config.html

解析并不是全部解析,如字体颜色等信息会丢失,图片比例会发生变化

yarn add @wangeditor/editor
yarn add @wangeditor/editor-for-react
# 用于将html转为word
yarn add html-docx-js-typescript

1、创建工具栏类

import { IButtonMenu, IDomEditor } from '@wangeditor/editor';
import { save } from '../icon';
class SaveWordMenu implements IButtonMenu {
    title: string;
    tag: string;
    iconSvg: string;
    constructor() {
        this.title = '另存为Word' // 自定义菜单标题
        this.iconSvg = save() // 图标
        this.tag = 'button'
    }

    /**
     * 获取编辑器内容源码
     * @param editor
     */
    getValue(editor: IDomEditor): string | boolean {
        return false;
    }

    /**
     * 菜单是否需要激活,当切换为源码时菜单激活
     * @param editor
     * @param active 激活状态
     */
    isActive(editor: IDomEditor, active?: boolean): boolean {
        return false;
    }

    /**
     * 菜单是否需要禁用(如选中 H1 ,“引用”菜单被禁用),用不到则返回 false
     * @param editor
     */
    isDisabled(editor: IDomEditor): boolean {
        return false;
    }

    /**
     * 点击菜单时触发的函数
     * @param editor
     * @param value
     */
    exec(editor: IDomEditor, value: string | boolean) {
        if (this.isDisabled(editor)) return
        editor.emit('clickSaveWord');
    }
}

export default SaveWordMenu;

2、工具栏方法实现

import SaveWordMenu from "./saveWord";
import { asBlob } from 'html-docx-js-typescript';

/**
 * 将富文本内容转为word
 * @param html 富文本内容
 */
export const saveWord = async (html: string) => {
    // 将富文本内容拼接为一个完整的html
    let value = `<!DOCTYPE html><html lang="en"><body style="font-family:方正仿宋_GBK,serif;mso-ascii-font-family:'Times New Roman';">${html}</body></html>`;
    // 将html转为word的blob
    const data = await asBlob(value, { orientation: 'landscape', margins: { top: 100 } });
    let aTag = document.createElement('a');
    // @ts-ignore
    aTag.href = (URL || webkitURL).createObjectURL(data);
    aTag.setAttribute('download', 'file.docx');
    aTag.click();
    // 下载后将标签移除
    aTag.remove();
}

export const saveConf = { 
    // 工具栏中的唯一key
    key: 'saveWord', 
    // 组件
    factory: () => new SaveWordMenu() 
};

3、页面具体代码

import { IDomEditor, Boot } from '@wangeditor/editor';
import { Editor, Toolbar } from '@wangeditor/editor-for-react';
import '@wangeditor/editor/dist/css/style.css';
import React, {useEffect, useState} from 'react';
import {saveWord, saveConf} from "./props";

const WangEditor = ({ value = '', mode = 'default', onChange, toolbarConfig = {} }: any) => {
    /***********自定义变量-------开始*************/
    // editor 实例
    const [editor, setEditor] = useState<IDomEditor | null>(null);
    // 编辑器内容
    const [html, setHtml] = useState<string>(value || '');
    /***********自定义变量-------结束*************/

    /***********生命周期函数-------开始*************/
    // 及时销毁 editor
    useEffect(() => {
        if (editor?.isFocused()) {
            editor?.blur();
        }
        return () => {
            // eslint-disable-next-line eqeqeq
            if (editor == null) return;
            editor.destroy();
            setEditor(null);
        };
    }, [editor]);

    const onCreated = (editor: IDomEditor) => {
        /*
         * 在组件创建时初始化注册菜单,注意菜单不可以重复注册否则会报异常
         * Unhandled Rejection (Error): Duplicated key 'source' in menu items
         */
        if (!editor.getAllMenuKeys().includes('saveWord')) {
            Boot.registerMenu(saveConf);
        }
        setEditor(editor);
        // 保存word
        editor?.on('clickSaveWord', () => saveWord(editor.getHtml()));
    }

    /***********生命周期函数-------结束*************/
    return (
        <div>
            <Toolbar
                editor={editor}
                defaultConfig={{
                    ...toolbarConfig,
                    // 添加自定义菜单
                    insertKeys: {
                        index: editor?.getAllMenuKeys().length || 0,
                        keys: ['saveWord'],
                    }
                }}
                mode={mode}
            />
            <Editor value={html} onCreated={onCreated} />
        </div>
    );
};

export default WangEditor;

效果图:https://blog.csdn.net/Ajie246862/article/details/132626711

 

posted @ 2023-09-04 10:18  ajie20999  阅读(665)  评论(0)    收藏  举报