记一次TinyMce6 需要支持复制WPS和office-Word文字图片处理方法

发布时间 2023-08-30 16:05:41作者: Texito

背景:

  客户一直在抱怨我们富文本编辑器复制不过来包含文字和图片的文档,一直是一个难题。

  找了半天,也用了wangEditor等其他富文本组件,发现都不行或者不能实现需求。

  最后发现TinyMce6有一个叫power_paste的官方插件,功能能较好的实现,但是要付费,而且体验了一下并不能从国民软件WPS中复制过来,所以还是没什么用。

发现:

  今天下午在逛Github的时候发现了一款新的TinyMce复制插件,而且是开源的,下面讲下使用方法。

开源地址:https://github.com/hanghang2/tinymce-pastewordimage

第一步:把当前plugins目录下的pastewordimage文件夹拷贝到你的项目tinymce/plugins目录下去;

例如react项目,路径为 项目根目录/public/tinymce/plugins/

第二步:tinymce初始化init配置plugins参属下增加pastewordimage;

// 如下增加pastewordimage参数

<Editor
    init={{
        branding: false, // 去掉右下角的水印
        menubar: true, // 菜单栏
        height: 500,
        plugins: [
            'advlist', 'autolink', 'lists', 'link', 'image', 'charmap', 'preview',
            'anchor', 'searchreplace', 'visualblocks', 'code', 'fullscreen',
            'insertdatetime', 'media', 'table', 'code', 'help', 'wordcount', 'codesample',
            'pastewordimage', // word复制图片插件
        ],
    }}
    initialValue="<p>This is the initial content of the editor.</p>"
    onInit={(evt, editor) => editorRef.current = editor}
    rootClassName={style.editor}
/>

第三步:版当前项目的tinymce.min.js文件拷贝到项目的tinymce目录中进行覆盖;

// 源码中 wps粘贴单个图片时候粘贴的内容中会有text/html类型,导致getDataTransferItems函数返回结果不正确;
// 修改如下:items[contentType]赋值增加判断;

const getDataTransferItems = dataTransfer => {
    const items = {};
    if (dataTransfer && dataTransfer.types) {
        for (let i = 0; i < dataTransfer.types.length; i++) {
            const contentType = dataTransfer.types[i];
            try {
                // items[contentType] = dataTransfer.getData(contentType);
                items[contentType] = dataTransfer.types.indexOf('Files') === -1 ? dataTransfer.getData(contentType) : ''; // wps粘贴单个图片问题处理
            } catch (ex) {
                items[contentType] = '';
            }
        }
    }
    return items;
};