黔东南网站开发,wordpress主题js,建设网站能赚钱,大连手机模板建站超级Word粘贴神器 - 专治CMS编辑头疼病
各位PHP老铁们好啊#xff01;我是江苏某不知名码农小王#xff0c;最近接了个企业官网改版项目#xff0c;客户爸爸提了个小需求——要在后台直接粘贴Word还能保留所有样式#xff01;这不#xff0c;我带着解决方案和…超级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 # 样式文件兼容IE82. 核心代码doc_magic.js—— 打工人亲自写的注释超详细// 注册TinyMCE插件Vue3/React通用复制就能用tinymce.PluginManager.add(doc_magic,function(editor,url){// 创建万能按钮用了阿里云同款绿好看constbtneditor.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/公众号内容CtrlV,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){constcontenttinymce.activeEditor.dom.get(pasteContent).value;// 调用后端APIPHP写的超简单constresawaitfetch(/api/doc/process-paste,{method:POST,headers:{Content-Type:application/json},body:JSON.stringify({content})});constdataawaitres.json();tinymce.activeEditor.dom.get(pastePreview).innerHTMLdata.content;// 显示预览}// 处理文件上传自动上传图片到OSSasyncfunctionhandleFileUpload(e,editor){constfilee.target.files[0];constformDatanewFormData();formData.append(file,file);// 调用后端上传接口PHP处理OSS上传constresawaitfetch(/api/doc/upload-file,{method:POST,body:formData});constdataawaitres.json();tinymce.activeEditor.dom.get(filePreview).innerHTMLdata.content;// 显示预览}// 抓取公众号内容自动下载图片asyncfunctionfetchWechatContent(editor){consturltinymce.activeEditor.dom.get(wechatUrl).value;constresawaitfetch(/api/doc/fetch-wechat,{method:POST,headers:{Content-Type:application/json},body:JSON.stringify({url})});constdataawaitres.json();tinymce.activeEditor.dom.get(wechatPreview).innerHTMLdata.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免费版够用Composercurl -sS https://getcomposer.org/installer | php -- --install-dir/usr/local/bin --filenamecomposer阿里云OSS SDKcomposer require aliyuncs/oss-sdk-php2. 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—— 打工人写的注释超详细ossConfigincludeconfig.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文档.docxpublicfunctionparseWord($filePath){$phpWordIOFactory::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晚的bugprivatefunctioncleanWordTags($html){returnpreg_replace([/.*?\/o:p/is,// 移除Word段落标记/classMso[^]*/is,// 移除Word样式类//is// 移除XML命名空间],[,,],$html);}// 辅助方法上传图片到OSS二进制存储非Base64privatefunctionuploadImages($html){preg_match_all(/]srcdata:image\/(png|jpg);base64,(.*?)\[^]*/,$html,$matches);foreach($matches[2]as$index$base64){$imageDatabase64_decode($matches[2][$index]);$tempFilesys_get_temp_dir()./img_.$index..png;file_put_contents($tempFile,$imageData);// 上传到OSS打工人写的方法超简单$ossUrl$this-uploadToOSS($tempFile,paste_img_.time()..png);$htmlstr_replace($matches[0][$index],,$html);unlink($tempFile);// 删除临时文件}return$html;}// 辅助方法上传文件到OSS打工人封装的超好用privatefunctionuploadToOSS($filePath,$fileName){$ossClientnewOssClient($this-ossConfig[oss_access_key],$this-ossConfig[oss_secret],$this-ossConfig[oss_endpoint]);$objectKeycms_docs/.$fileName;// 存储路径cms_docs/文件名try{$ossClient-uploadFile($this-ossConfig[oss_bucket],$objectKey,$filePath);returnhttps://{$this-ossConfig[oss_bucket]}.{$this-ossConfig[oss_endpoint]}/{$objectKey};}catch(Exception$e){return上传失败.$e-getMessage();}}// 辅助方法Latex转MathML调用MathJax免费APIprivatefunctionconvertLatexToMathML($html){returnpreg_replace_callback(/\$(.*?)\$/is,function($matches){$latex$matches[1];try{// 调用MathJax API免费实测可用$mathmlfile_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([code0,content$result]);break;caseupload-file:$file$_FILES[file];$tempPath$file[tmp_name];$fileNamebasename($file[name]);// 保存临时文件file_put_contents($tempPath,file_get_contents($file[tmp_name]));// 解析文件打工人写的支持Word/Excel/PPT/PDF$htmlmatch(strtolower(pathinfo($fileName,PATHINFO_EXTENSION))){docx$processor-parseWord($tempPath),pdf$this-parsePdf($tempPath),// 打工人说PDF解析太复杂这里简化default暂不支持的文件格式};echojson_encode([code0,content$html]);break;default:echojson_encode([code400,msg无效操作]);break;}// 打工人说PDF解析太麻烦这里留个坑下次更新补functionparsePdf($filePath){returnPDF内容预览打工人下次更新;}?四、部署指南打工人手把手教5分钟搞定1. 环境搭建宿舍电脑/实验室服务器安装PHP 7.4https://windows.php.net/download/安装MySQL 5.7https://dev.mysql.com/downloads/mysql/安装Composerhttps://getcomposer.org/注册阿里云OSShttps://oss.console.aliyun.com/创建Bucket并获取AccessKey2. 集成步骤复制粘贴就能用把doc_magic插件文件夹丢进TinyMCE的plugins目录路径tinymce/plugins/在TinyMCE初始化配置tinymce.init.js中添加按钮tinymce.init({selector:#editor,// 你的编辑器容器IDplugins:doc_magic,// 添加插件toolbar:doc_magic bold italic// 工具栏显示按钮});把config.php中的OSS信息改成你自己的阿里云控制台获取把项目放到Zend Studio中运行php -S localhost:8080启动内置服务器五、群组福利打工人建的专搞外包加群223813913解锁以下隐藏福利新人红包1~99元随机现金手慢无打工人自己发的接单特权优先获取企业CMS外包项目单价1k~5k打工人带飞提成暴击推荐客户拿20%提成1万订单直接拿2k打工人算过一个月接5单够生活费内推通道打工人在上海软件园有资源国企/事业单位技术岗直推月薪8k群友真实反馈“上周推荐了个政府项目提成拿了3k够买台新笔记本了”六、打工人的碎碎念避坑指南图片上传一定要用二进制存储非Base64前端HTML会膨胀10倍Word解析PhpWord对复杂样式支持一般打工人实测简单文档没问题复杂文档建议用WPS转HTMLLatex转换MathJax API偶尔抽风打工人加了重试机制代码里有注释兼容性IE8需要开兼容模式打工人测试过没问题别骂了打工人尽力了成本控制全套方案成本Mammoth.js (免费)TinyMCE (基础版免费)阿里云OSS (费用极低)开发时间2天老板给的680刚好够买几杯咖啡提神加群福利各位老铁这个方案我已经在QQ群223813913分享了完整代码前端Vue3完整组件后端PHP完整类OSS配置指南部署避坑指南现在加群还能领1-99元红包一起接单一起嗨下个月房贷就靠各位老板带飞了PS老板们总说这个功能很简单但只有咱们程序员知道这Word粘贴功能堪比在代码里养了一只霸王龙还得让它跳芭蕾复制插件安装jquerynpm install jquery在组件中引入// 引入tinymce-vueimportEditorfromtinymce/tinymce-vueimport{WordPaster}from../../static/WordPaster/js/wimport{zyOffice}from../../static/zyOffice/js/oimport{zyCapture}from../../static/zyCapture/z添加工具栏//添加导入excel工具栏按钮(function(){use strict;varglobaltinymce.util.Tools.resolve(tinymce.PluginManager);functionselectLocalImages(editor){WordPaster.getInstance().SetEditor(editor).importExcel()}varregister$1function(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;varglobaltinymce.util.Tools.resolve(tinymce.PluginManager);functionselectLocalImages(editor){WordPaster.getInstance().SetEditor(editor);WordPaster.getInstance().importWordToImg()}varregister$1function(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;varglobaltinymce.util.Tools.resolve(tinymce.PluginManager);functionselectLocalImages(editor){WordPaster.getInstance().SetEditor(editor);WordPaster.getInstance().UploadNetImg()}varregister$1function(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;varglobaltinymce.util.Tools.resolve(tinymce.PluginManager);functionselectLocalImages(editor){WordPaster.getInstance().SetEditor(editor);WordPaster.getInstance().ImportPDF()}varregister$1function(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;varglobaltinymce.util.Tools.resolve(tinymce.PluginManager);functionselectLocalImages(editor){WordPaster.getInstance().SetEditor(editor);WordPaster.getInstance().importPPT()}varregister$1function(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;varglobaltinymce.util.Tools.resolve(tinymce.PluginManager);functionselectLocalImages(editor){WordPaster.getInstance().SetEditor(editor).importWord()}varregister$1function(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;varglobaltinymce.util.Tools.resolve(tinymce.PluginManager);varicohttp://localhost:8080/static/WordPaster/plugin/word.pngfunctionselectLocalImages(editor){WordPaster.getInstance().SetEditor(editor).PasteManual()}varregister$1function(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 visualcharsdefault:autoresize code autolink autosave image imagetools paste preview table powertables},点击查看在线代码初始化组件// 初始化WordPaster.getInstance({// 上传接口http://www.ncmem.com/doc/view.aspx?idd88b60a2b0204af1ba62fa66288203edPostUrl:http://localhost:8891/upload.aspx,// 为图片地址增加域名http://www.ncmem.com/doc/view.aspx?id704cd302ebd346b486adf39cf4553936ImageUrl:http://localhost:8891{url},// 设置文件字段名称http://www.ncmem.com/doc/view.aspx?idc3ad06c2ae31454cb418ceb2b8da7c45FileFieldName:file,// 提取图片地址http://www.ncmem.com/doc/view.aspx?id07e3f323d22d4571ad213441ab8530d1ImageMatch:})在页面中引入组件功能演示编辑器在编辑器中增加功能按钮导入Word文档,支持doc,docx导入Excel文档,支持xls,xlsx粘贴Word一键粘贴Word内容自动上传Word中的图片保留文字样式。Word转图片一键导入Word文件并将Word文件转换成图片上传到服务器中。导入PDF一键导入PDF文件并将PDF转换成图片上传到服务器中。导入PPT一键导入PPT文件并将PPT转换成图片上传到服务器中。上传网络图片一键自动上传网络图片。下载示例点击下载完整示例