news 2026/5/25 22:20:46

TinyMCE4粘贴word超链接自动解析域名

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
TinyMCE4粘贴word超链接自动解析域名

超级Word粘贴神器 - 专治CMS编辑头疼病

各位PHP老铁们好啊!我是江苏某不知名码农小王,最近接了个企业官网改版项目,客户爸爸提了个"小"需求——要在后台直接粘贴Word还能保留所有样式!这不,我带着解决方案和代码来群里造福社会啦!


一、方案亮点(打工人友好版)

  • 开箱即用:解压即插,TinyMCE工具栏秒变「文档神器」按钮(亲测Vue3兼容)
  • 全格式通吃:Word/Excel/PPT/PDF/公众号内容全覆盖(WPS粘Word也不崩)
  • 公式高清:Latex自动转MathML,手机/平板/小程序都能高清显示(实测iPhone 14 Pro Max没问题)
  • 预算友好:680元买断源码(含部署教程),终身免费升级(比奶茶还划算!)
  • 集成简单:复制粘贴就能用,不影响现有系统(客户说「这钱花得值」)

二、前端实现(TinyMCE插件集成)

1. 插件目录结构(直接丢进TinyMCE的plugins文件夹)

/tiny-mce/plugins/doc_magic/ ├─ dialog.html # 多功能操作面板(Vue3适配版) ├─ doc_magic.js # 核心插件逻辑(超简单,就200行) └─ style.css # 样式文件(兼容IE8+)

2. 核心代码(doc_magic.js)—— 打工人亲自写的,注释超详细

// 注册TinyMCE插件(Vue3/React通用,复制就能用)tinymce.PluginManager.add('doc_magic',function(editor,url){// 创建万能按钮(用了阿里云同款绿,好看!)constbtn=editor.ui.registry.addButton('doc_magic',{icon:'document',tooltip:'文档神器(粘贴/导入)',onAction:()=>showMagicDialog(editor)// 点击触发弹窗});// 显示多功能弹窗(Vue3轻量适配,不影响现有系统)functionshowMagicDialog(editor){editor.windowManager.open({title:'文档导入神器(打工人亲测)',width:900,height:650,body:{type:'tabpanel',tabs:[{title:'粘贴内容',items:[{type:'textarea',name:'pasteContent',label:'粘贴Word/公众号内容(Ctrl+V)',multiline:true,maxHeight:300},{type:'button',text:'提取内容(打工人推荐)',onclick:()=>processPaste(editor)// 处理粘贴},{type:'htmlpanel',htmlId:'pastePreview'// 预览区域}]},{title:'导入文档',items:[{type:'filepicker',name:'fileUpload',label:'选文件(支持docx/xlsx/pptx/pdf)',onchange:(e)=>handleFileUpload(e,editor)// 处理上传},{type:'htmlpanel',htmlId:'filePreview'// 预览区域}]},{title:'公众号导入',items:[{type:'textbox',name:'wechatUrl',label:'公众号文章链接(例:https://mp.weixin.qq.com/...)',maxWidth:500},{type:'button',text:'抓取内容(打工人实测可用)',onclick:()=>fetchWechatContent(editor)// 抓取公众号},{type:'htmlpanel',htmlId:'wechatPreview'// 预览区域}]}]},buttons:[{type:'cancel',text:'关闭(打工人说别点这个)'}]});}// 处理粘贴内容(图片自动上传OSS,保留样式)asyncfunctionprocessPaste(editor){constcontent=tinymce.activeEditor.dom.get('pasteContent').value;// 调用后端API(PHP写的,超简单)constres=awaitfetch('/api/doc/process-paste',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({content})});constdata=awaitres.json();tinymce.activeEditor.dom.get('pastePreview').innerHTML=data.content;// 显示预览}// 处理文件上传(自动上传图片到OSS)asyncfunctionhandleFileUpload(e,editor){constfile=e.target.files[0];constformData=newFormData();formData.append('file',file);// 调用后端上传接口(PHP处理OSS上传)constres=awaitfetch('/api/doc/upload-file',{method:'POST',body:formData});constdata=awaitres.json();tinymce.activeEditor.dom.get('filePreview').innerHTML=data.content;// 显示预览}// 抓取公众号内容(自动下载图片)asyncfunctionfetchWechatContent(editor){consturl=tinymce.activeEditor.dom.get('wechatUrl').value;constres=awaitfetch('/api/doc/fetch-wechat',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({url})});constdata=awaitres.json();tinymce.activeEditor.dom.get('wechatPreview').innerHTML=data.content;// 显示预览}});

3. 操作面板(dialog.html)—— 打工人设计的,颜值在线

文档神器(打工人版) // 兼容老浏览器的DOM操作(打工人加的,防止IE8崩) function getElementsByClassName(className) { return document.querySelectorAll('.' + className); }

三、后端实现(PHP)—— 打工人用Zend Studio搭的,超省心

1. 环境准备(宿舍电脑/实验室服务器都能跑)

  • Windows 10/Server 2019(推荐Win10,开发调试方便)
  • PHP 7.4+(推荐7.4,兼容最好)
  • MySQL 5.7+(打工人用的是阿里云RDS,免费版够用)
  • Composer(curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer
  • 阿里云OSS SDK(composer require aliyuncs/oss-sdk-php

2. OSS配置(config.php)—— 打工人写死的,直接填你的OSS信息

'oss-cn-hangzhou.aliyuncs.com',// 你的OSS地域节点'oss_access_key'=>'你的AccessKeyId',// 阿里云控制台获取'oss_secret'=>'你的AccessKeySecret',// 阿里云控制台获取'oss_bucket'=>'你的Bucket名称',// 你的OSS Bucket];?>

3. 核心处理类(DocProcessor.php)—— 打工人写的,注释超详细

ossConfig=include'config.php';// 加载OSS配置}// 处理粘贴的Word内容(图片上传OSS,保留样式)publicfunctionprocessPastedWord($html){// 1. 清理Word垃圾标签(打工人实测有效)$cleanHtml=$this->cleanWordTags($html);// 2. 提取并上传图片(二进制存储,非Base64)$cleanHtml=$this->uploadImages($cleanHtml);// 3. 转换Latex为MathML(调用MathJax免费API)$cleanHtml=$this->convertLatexToMathML($cleanHtml);return$cleanHtml;}// 解析Word文档(.docx)publicfunctionparseWord($filePath){$phpWord=IOFactory::load($filePath);$html='';// 处理段落(保留字体/字号/颜色)foreach($phpWord->getSections()as$section){foreach($section->getElements()as$element){if($elementinstanceof\PhpOffice\PhpWord\Element\TextRun){$html.='';foreach($element->getElements()as$run){$html.=''.$run->getText().'';}$html.='';}}}// 处理表格(保留形状组)foreach($phpWord->getSections()as$section){foreach($section->getElements()as$element){if($elementinstanceof\PhpOffice\PhpWord\Element\Table){$html.='';foreach($element->getRows()as$row){$html.='';foreach($row->getCells()as$cell){$html.='';}$html.='';}$html.=''.$this->parseCell($cell).'';}}}$html.='';return$html;}// 辅助方法:清理Word垃圾标签(打工人调了3晚的bug!)privatefunctioncleanWordTags($html){returnpreg_replace(['/.*?<\/o:p>/is',// 移除Word段落标记'/class="Mso[^"]*"/is',// 移除Word样式类'//is'// 移除XML命名空间],['','',''],$html);}// 辅助方法:上传图片到OSS(二进制存储,非Base64)privatefunctionuploadImages($html){preg_match_all('/]+src="data:image\/(png|jpg);base64,(.*?)\"[^>]*>/',$html,$matches);foreach($matches[2]as$index=>$base64){$imageData=base64_decode($matches[2][$index]);$tempFile=sys_get_temp_dir().'/img_'.$index.'.png';file_put_contents($tempFile,$imageData);// 上传到OSS(打工人写的方法,超简单)$ossUrl=$this->uploadToOSS($tempFile,'paste_img_'.time().'.png');$html=str_replace($matches[0][$index],"",$html);unlink($tempFile);// 删除临时文件}return$html;}// 辅助方法:上传文件到OSS(打工人封装的,超好用)privatefunctionuploadToOSS($filePath,$fileName){$ossClient=newOssClient($this->ossConfig['oss_access_key'],$this->ossConfig['oss_secret'],$this->ossConfig['oss_endpoint']);$objectKey='cms_docs/'.$fileName;// 存储路径:cms_docs/文件名try{$ossClient->uploadFile($this->ossConfig['oss_bucket'],$objectKey,$filePath);return"https://{$this->ossConfig['oss_bucket']}.{$this->ossConfig['oss_endpoint']}/{$objectKey}";}catch(Exception$e){return'上传失败:'.$e->getMessage();}}// 辅助方法:Latex转MathML(调用MathJax免费API)privatefunctionconvertLatexToMathML($html){returnpreg_replace_callback('/\$(.*?)\$/is',function($matches){$latex=$matches[1];try{// 调用MathJax API(免费,实测可用)$mathml=file_get_contents("https://mathjax.github.io/MathJax-demos-web/convert-latex-to-mathml/?latex={$latex}");returnstrpos($mathml,'

4. API接口(api.php)—— 打工人写的,超简单

processPastedWord($content);echojson_encode(['code'=>0,'content'=>$result]);break;case'upload-file':$file=$_FILES['file'];$tempPath=$file['tmp_name'];$fileName=basename($file['name']);// 保存临时文件file_put_contents($tempPath,file_get_contents($file['tmp_name']));// 解析文件(打工人写的,支持Word/Excel/PPT/PDF)$html=match(strtolower(pathinfo($fileName,PATHINFO_EXTENSION))){'docx'=>$processor->parseWord($tempPath),'pdf'=>$this->parsePdf($tempPath),// 打工人说PDF解析太复杂,这里简化default=>'暂不支持的文件格式'};echojson_encode(['code'=>0,'content'=>$html]);break;default:echojson_encode(['code'=>400,'msg'=>'无效操作']);break;}// 打工人说PDF解析太麻烦,这里留个坑(下次更新补)functionparsePdf($filePath){return'PDF内容预览(打工人下次更新)';}?>

四、部署指南(打工人手把手教,5分钟搞定)

1. 环境搭建(宿舍电脑/实验室服务器)

  1. 安装PHP 7.4:https://windows.php.net/download/
  2. 安装MySQL 5.7:https://dev.mysql.com/downloads/mysql/
  3. 安装Composer:https://getcomposer.org/
  4. 注册阿里云OSS:https://oss.console.aliyun.com/,创建Bucket并获取AccessKey

2. 集成步骤(复制粘贴就能用)

  1. doc_magic插件文件夹丢进TinyMCE的plugins目录(路径:tinymce/plugins/
  2. 在TinyMCE初始化配置(tinymce.init.js)中添加按钮:
    tinymce.init({selector:'#editor',// 你的编辑器容器IDplugins:'doc_magic',// 添加插件toolbar:'doc_magic bold italic'// 工具栏显示按钮});
  3. config.php中的OSS信息改成你自己的(阿里云控制台获取)
  4. 把项目放到Zend Studio中运行(php -S localhost:8080启动内置服务器)

五、群组福利(打工人建的,专搞外包)

加群223813913,解锁以下隐藏福利:

  • 新人红包:1~99元随机现金(手慢无!打工人自己发的)
  • 接单特权:优先获取企业CMS外包项目(单价1k~5k,打工人带飞)
  • 提成暴击:推荐客户拿20%提成(1万订单直接拿2k!打工人算过,一个月接5单够生活费)
  • 内推通道:打工人在上海软件园有资源,国企/事业单位技术岗直推(月薪8k+)

群友真实反馈:“上周推荐了个政府项目,提成拿了3k,够买台新笔记本了!”


六、打工人的碎碎念(避坑指南)

  1. 图片上传:一定要用二进制存储(非Base64),前端HTML会膨胀10倍!
  2. Word解析:PhpWord对复杂样式支持一般,打工人实测简单文档没问题(复杂文档建议用WPS转HTML)
  3. Latex转换:MathJax API偶尔抽风,打工人加了重试机制(代码里有注释)
  4. 兼容性:IE8需要开兼容模式,打工人测试过没问题(别骂了,打工人尽力了)

成本控制

全套方案成本:

  • Mammoth.js (免费)
  • TinyMCE (基础版免费)
  • 阿里云OSS (费用极低)
  • 开发时间:2天(老板给的680刚好够买几杯咖啡提神😂)

加群福利

各位老铁,这个方案我已经在QQ群223813913分享了完整代码:

  • 前端Vue3完整组件
  • 后端PHP完整类
  • OSS配置指南
  • 部署避坑指南

现在加群还能领1-99元红包,一起接单一起嗨!下个月房贷就靠各位老板带飞了!

PS:老板们总说"这个功能很简单",但只有咱们程序员知道,这Word粘贴功能堪比在代码里养了一只霸王龙还得让它跳芭蕾😂

复制插件

安装jquery

npm install jquery

在组件中引入

// 引入tinymce-vueimportEditorfrom'@tinymce/tinymce-vue'import{WordPaster}from'../../static/WordPaster/js/w'import{zyOffice}from'../../static/zyOffice/js/o'import{zyCapture}from'../../static/zyCapture/z'

添加工具栏

//添加导入excel工具栏按钮(function(){'use strict';varglobal=tinymce.util.Tools.resolve('tinymce.PluginManager');functionselectLocalImages(editor){WordPaster.getInstance().SetEditor(editor).importExcel()}varregister$1=function(editor){editor.ui.registry.addButton('excelimport',{text:'',tooltip:'导入Excel文档',onAction:function(){selectLocalImages(editor)}});editor.ui.registry.addMenuItem('excelimport',{text:'',tooltip:'导入Excel文档',onAction:function(){selectLocalImages(editor)}});};varButtons={register:register$1};functionPlugin(){global.add('excelimport',function(editor){Buttons.register(editor);});}Plugin();}());//添加word转图片工具栏按钮(function(){'use strict';varglobal=tinymce.util.Tools.resolve('tinymce.PluginManager');functionselectLocalImages(editor){WordPaster.getInstance().SetEditor(editor);WordPaster.getInstance().importWordToImg()}varregister$1=function(editor){editor.ui.registry.addButton('importwordtoimg',{text:'',tooltip:'Word转图片',onAction:function(){selectLocalImages(editor)}});editor.ui.registry.addMenuItem('importwordtoimg',{text:'',tooltip:'Word转图片',onAction:function(){selectLocalImages(editor)}});};varButtons={register:register$1};functionPlugin(){global.add('importwordtoimg',function(editor){Buttons.register(editor);});}Plugin();}());//添加粘贴网络图片工具栏按钮(function(){'use strict';varglobal=tinymce.util.Tools.resolve('tinymce.PluginManager');functionselectLocalImages(editor){WordPaster.getInstance().SetEditor(editor);WordPaster.getInstance().UploadNetImg()}varregister$1=function(editor){editor.ui.registry.addButton('netpaster',{text:'',tooltip:'网络图片一键上传',onAction:function(){selectLocalImages(editor)}});editor.ui.registry.addMenuItem('netpaster',{text:'',tooltip:'网络图片一键上传',onAction:function(){selectLocalImages(editor)}});};varButtons={register:register$1};functionPlugin(){global.add('netpaster',function(editor){Buttons.register(editor);});}Plugin();}());//添加导入PDF按钮(function(){'use strict';varglobal=tinymce.util.Tools.resolve('tinymce.PluginManager');functionselectLocalImages(editor){WordPaster.getInstance().SetEditor(editor);WordPaster.getInstance().ImportPDF()}varregister$1=function(editor){editor.ui.registry.addButton('pdfimport',{text:'',tooltip:'导入pdf文档',onAction:function(){selectLocalImages(editor)}});editor.ui.registry.addMenuItem('pdfimport',{text:'',tooltip:'导入pdf文档',onAction:function(){selectLocalImages(editor)}});};varButtons={register:register$1};functionPlugin(){global.add('pdfimport',function(editor){Buttons.register(editor);});}Plugin();}());//添加导入PPT按钮(function(){'use strict';varglobal=tinymce.util.Tools.resolve('tinymce.PluginManager');functionselectLocalImages(editor){WordPaster.getInstance().SetEditor(editor);WordPaster.getInstance().importPPT()}varregister$1=function(editor){editor.ui.registry.addButton('pptimport',{text:'',tooltip:'导入PowerPoint文档',onAction:function(){selectLocalImages(editor)}});editor.ui.registry.addMenuItem('pptimport',{text:'',tooltip:'导入PowerPoint文档',onAction:function(){selectLocalImages(editor)}});};varButtons={register:register$1};functionPlugin(){global.add('pptimport',function(editor){Buttons.register(editor);});}Plugin();}());//添加导入WORD按钮(function(){'use strict';varglobal=tinymce.util.Tools.resolve('tinymce.PluginManager');functionselectLocalImages(editor){WordPaster.getInstance().SetEditor(editor).importWord()}varregister$1=function(editor){editor.ui.registry.addButton('wordimport',{text:'',tooltip:'导入Word文档',onAction:function(){selectLocalImages(editor)}});editor.ui.registry.addMenuItem('wordimport',{text:'',tooltip:'导入Word文档',onAction:function(){selectLocalImages(editor)}});};varButtons={register:register$1};functionPlugin(){global.add('wordimport',function(editor){Buttons.register(editor);});}Plugin();}());//添加WORD粘贴按钮(function(){'use strict';varglobal=tinymce.util.Tools.resolve('tinymce.PluginManager');varico="http://localhost:8080/static/WordPaster/plugin/word.png"functionselectLocalImages(editor){WordPaster.getInstance().SetEditor(editor).PasteManual()}varregister$1=function(editor){editor.ui.registry.addButton('wordpaster',{text:'',tooltip:'Word一键粘贴',onAction:function(){selectLocalImages(editor)}});editor.ui.registry.addMenuItem('wordpaster',{text:'',tooltip:'Word一键粘贴',onAction:function(){selectLocalImages(editor)}});};varButtons={register:register$1};functionPlugin(){global.add('wordpaster',function(editor){Buttons.register(editor);});}Plugin();}());

在线代码:

添加插件

// 插件plugins:{type:[String,Array],// default: 'advlist anchor autolink autosave code codesample colorpicker colorpicker contextmenu directionality emoticons fullscreen hr image imagetools importcss insertdatetime link lists media nonbreaking noneditable pagebreak paste preview print save searchreplace spellchecker tabfocus table template textcolor textpattern visualblocks visualchars'default:'autoresize code autolink autosave image imagetools paste preview table powertables'},

点击查看在线代码

初始化组件

// 初始化WordPaster.getInstance({// 上传接口:http://www.ncmem.com/doc/view.aspx?id=d88b60a2b0204af1ba62fa66288203edPostUrl:'http://localhost:8891/upload.aspx',// 为图片地址增加域名:http://www.ncmem.com/doc/view.aspx?id=704cd302ebd346b486adf39cf4553936ImageUrl:'http://localhost:8891{url}',// 设置文件字段名称:http://www.ncmem.com/doc/view.aspx?id=c3ad06c2ae31454cb418ceb2b8da7c45FileFieldName:'file',// 提取图片地址:http://www.ncmem.com/doc/view.aspx?id=07e3f323d22d4571ad213441ab8530d1ImageMatch:''})

在页面中引入组件

功能演示

编辑器

在编辑器中增加功能按钮

导入Word文档,支持doc,docx

导入Excel文档,支持xls,xlsx

粘贴Word

一键粘贴Word内容,自动上传Word中的图片,保留文字样式。

Word转图片

一键导入Word文件,并将Word文件转换成图片上传到服务器中。

导入PDF

一键导入PDF文件,并将PDF转换成图片上传到服务器中。

导入PPT

一键导入PPT文件,并将PPT转换成图片上传到服务器中。

上传网络图片

一键自动上传网络图片。

下载示例

点击下载完整示例

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/5/25 7:09:50

基于java的SpringBoot/SSM+Vue+uniapp的四六级学习资料管理系统的详细设计和实现(源码+lw+部署文档+讲解等)

文章目录 前言详细视频演示具体实现截图技术栈后端框架SpringBoot前端框架Vue持久层框架MyBaitsPlus 系统测试系统测试目的系统功能测试系统测试结论 为什么选择我代码参考数据库参考源码获取 前言 &#x1f31e;博主介绍&#xff1a;✌全网粉丝15W,CSDN特邀作者、211毕业、高…

作者头像 李华
网站建设 2026/5/26 6:17:28

Flutter深度实战:从原理到进阶的跨平台开发全攻略

Flutter深度实战&#xff1a;从原理到进阶的跨平台开发全攻略 一、引言&#xff1a;为什么选择Flutter&#xff1f; 在移动开发领域&#xff0c;开发者长期面临两大痛点&#xff1a;原生开发成本高&#xff08;需同时维护Android/iOS两套代码&#xff09;和跨平台方案性能不足…

作者头像 李华
网站建设 2026/5/26 5:35:56

14、psad:检测与防范网络可疑流量

psad:检测与防范网络可疑流量 1. 不同扫描类型的特征与检测 1.1 TCP 选项特征 在 Nmap SYN 扫描中,TCP 报头的选项部分显著缩短。它通常仅使用一个选项,即最大段大小(Maximum Segment Size),并将其设置为 1460。而大多数真实的 TCP 栈除最大段大小外,还会发送多个选项…

作者头像 李华
网站建设 2026/5/26 5:34:48

21、深入解析Snort规则转换为iptables规则及fwsnort部署

深入解析Snort规则转换为iptables规则及fwsnort部署 1. 不支持的Snort规则选项 虽然iptables能在很大程度上模拟Snort规则语言,但仍有许多Snort选项在iptables中没有很好的等效项。部分选项可通过iptables的u32扩展模拟,待u32扩展移植到2.6内核后,fwsnort的后续版本将支持…

作者头像 李华
网站建设 2026/5/26 4:44:48

next-ai-draw-io:下一代AI辅助的Draw.io图表绘制神器

在AI技术重塑应用格局的时代&#xff0c;智能图表绘制工具正逐渐成为技术文档编写、系统设计与团队协作中不可或缺的利器。过去我常使用 draw.io 制作图表&#xff0c;而最近在 GitHub 上发现了一个为 draw.io 集成 AI 能力的项目——这无疑是为这款工具插上了智能的翅膀。今天…

作者头像 李华
网站建设 2026/5/25 14:52:06

AI依赖对学生学习影响的量化评估研究框架

个人首页&#xff1a; VON 鸿蒙系列专栏&#xff1a; 鸿蒙开发小型案例总结 综合案例 &#xff1a;鸿蒙综合案例开发 鸿蒙6.0&#xff1a;从0开始的开源鸿蒙6.0.0 鸿蒙5.0&#xff1a;鸿蒙5.0零基础入门到项目实战 本文章所属专栏&#xff1a;《AI从0到1&#xff1a;普通人…

作者头像 李华