富文本編輯器新增導入word功能,自動轉爲html,可直接顯示圖片

用我如今最常使用的php框架fastadmin舉例子,固然thinkphp或者原生php也是一樣的原理,你們理解思路就行了、php

 

環境:fastadmin,summernote編輯器
【summernote的居中功能在段落裏,且不會吃掉section標籤,加上導入word功能以後,簡直完美~】
 
按照國際慣例先放效果圖
 
 
github上的demo裏我尚未換圖標,不過fastadmin裏的是換了的,效果以下:
 
 
 

一、thinkphp使用composer安裝phpword插件(這個插件可以把word轉爲html)html

composer require phpoffice/phpword

安裝完成以後的文件在vender目錄下node

 

二、打開require統一管理後臺插件的jsjquery

引入咱們須要的ajaxfileupload.js插件(這個插件容許文件經過ajax上傳到服務器,而不是form表單)git

'ajaxfileupload':'../libs/ajaxfileupload/ajaxfileupload',

 

三、以新增新聞的編輯器爲例,打開github

 在開頭載入須要的組件ajax

define(['jquery', 'bootstrap', 'backend', 'table', 'form','summernote','layer','ajaxfileupload'], function ($, undefined, Backend, Table, Form,summernote,layer,ajaxfileupload) {

 

而後修改add方法thinkphp

add: function () { Controller.api.bindevent(); var imageButton = function (context) { var ui = $.summernote.ui; var button = ui.button({ contents: '<i class="fa fa-file-image-o"/>', tooltip: __('Choose'), click: function () { parent.Fast.api.open("general/attachmentlect?element_id=&multiple=true&mimetype=image/*", __('Choose'), { callback: function (data) { var urlArr = data.url.split(/\,/); $.each(urlArr, function () { var url = Fast.api.cdnurl(this); context.invoke('editor.insertImage', url); }); } }); return false; } }); return button.render(); }; var attachmentButton = function (context) { var ui = $.summernote.ui; var button = ui.button({ contents: '<i class="fa fa-file"/>', tooltip: __('Choose'), click: function () { parent.Fast.api.open("general/attachmentlect?element_id=&multiple=true&mimetype=*", __('Choose'), { callback: function (data) { var urlArr = data.url.split(/\,/); $.each(urlArr, function () { var url = Fast.api.cdnurl(this); var node = $("<a href='" + url + "'>" + url + "</a>"); context.invoke('insertNode', node[0]); }); } }); return false; } }); return button.render(); }; // 新增編輯器導入word功能
    var wordBtn = function (context) { var ui = $.summernote.ui; var button = ui.button({ contents: '<i class="fa fa-file-word-o"/>', tooltip: '導入word', click: function () { // 點擊以後的操做
                layer.open({ type: 1, skin: 'layui-layer-rim', //加上邊框
                    area: ['420px', '160px'], //寬高
                    content: '<input type="file" id="file" name="file" title="上傳word" value="" ><br/><input type="button" value="上傳" id="submit" />' }); } }); return button.render();   // return button as jquery object
 }; $(".summernote,.editor", $('form')).summernote({ height: 250, lang: 'zh-CN', fontNames: [ 'Arial', 'Arial Black', 'Serif', 'Sans', 'Courier',
            'Courier New', 'Comic Sans MS', 'Helvetica', 'Impact', 'Lucida Grande',
            "Open Sans", "Hiragino Sans GB", "Microsoft YaHei",
            '微軟雅黑', '宋體', '黑體', '仿宋', '楷體', '幼圓', ], fontNamesIgnoreCheck: [ "Open Sans", "Microsoft YaHei",
            '微軟雅黑', '宋體', '黑體', '仿宋', '楷體', '幼圓' ], toolbar: [ ['style', ['style', 'undo', 'redo']], ['font', ['bold', 'underline', 'strikethrough', 'clear']], ['fontname', ['color', 'fontname', 'fontsize']], ['para', ['ul', 'ol', 'paragraph', 'height']], ['table', ['table', 'hr']], ['insert', ['link', 'picture', 'video']], ['select', ['image', 'attachment']], ['view', ['fullscreen', 'codeview', 'help','word']], ], buttons: { image: imageButton, attachment: attachmentButton, word:wordBtn }, dialogsInBody: true, followingToolbar: false, callbacks: { onChange: function (contents) { $(this).val(contents); $(this).trigger('change'); }, onInit: function () { }, onImageUpload: function (files) { var that = this; //依次上傳圖片
                for (var i = 0; i < files.length; i++) { Upload.api.send(files[i], function (data) { var url = Fast.api.cdnurl(data.url); $(that).summernote("insertImage", url, 'filename'); }); } } } }); // 點擊上傳按鈕,發送ajax,上傳word文檔,並獲取到返回的html地址 // 動態生成的元素須要使用在document上加點擊事件
    $(document).on('click','#submit',function(){ var path = $('#file').val(); if ($.trim(path) == "") { alert("請選擇要上傳的文件"); return; } $.ajaxFileUpload({ url: 'form',  //這裏是服務器處理的代碼
            type: 'post', secureuri: false, //通常設置爲false
            fileElementId: 'file', // 上傳文件的id、name屬性名
            dataType: 'json', //返回值類型,通常設置爲json、application/json
            success: function (data, status) { console.log('success') }, error:function(data, status, e){ console.log('error') var responseText = data.responseText; // console.log(responseText); // 把html賦值給富文本,,並關閉layui
                $('.layui-layer-close').click(); $(".summernote,.editor", $('form')).summernote('code',responseText); } }); }); },
 

 

 

四、修改控制器json

use PhpOffice\PhpWord\PhpWord; ...

public function form(){ // 接收表單上傳的文件,並存儲到服務器中
    $file = $_FILES['file']['tmp_name'];//上傳的文件
    move_uploaded_file($file,"/words/res.docx"); // 使用phpword將word轉爲html
    $phpWord = IOFactory::load('/words/res.docx'); $xmlWriter = IOFactory::createWriter($phpWord, "HTML"); $resPath = '/words/res.html'; $xmlWriter->save($resPath); $html = file_get_contents($resPath); return $html; }
 
五、記得public目錄下建立一個words文件夾,用來存儲word和html文件
 
----------------------------------------------------------------------------------------
 
實踐過程當中發現base64格式的代碼太長、太佔空間,因而決定將base64格式的圖片轉爲普通格式的圖片,存入服務器
 
一、修改phpoffice\phpword\src\PhpWord\Element\Image.php
在這個類文件的最後新增一個方法,用於將base64格式的圖片轉爲普通格式圖片存入服務器
public function base64_image_content($base64_image_content,$path){ //匹配出圖片的格式
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)){ $type = $result[2]; $new_file = $path."/".date('Ymd',time())."/"; if(!file_exists($new_file)){ //檢查是否有該文件夾,若是沒有就建立,並給予最高權限
                mkdir($new_file, 0700); } $new_file = $new_file.time().".{$type}"; if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_image_content)))){ return '/'.$new_file; }else{ return false; } }else{ return false; } }
 
二、提早建立好存放圖片的文件夾
D:/phpstudy_pro/WWW/word/public/word_images
 
三、修改phpoffice\phpword\src\PhpWord\Writer\HTML\Element\Image.php
原先是將圖片以base64格式返回的,改成html裏訪問服務器圖片的格式並返回
public function write() { if (!$this->element instanceof ImageElement) { return ''; } $content = ''; $imageData = $this->element->getImageStringData(true); if ($imageData !== null) { $styleWriter = new ImageStyleWriter($this->element->getStyle()); $style = $styleWriter->write(); $imageData = 'data:' . $this->element->getImageType() . ';base64,' . $imageData; // 一、獲取到項目根目錄 // ---- D:/phpstudy_pro/WWW/word/vendor/phpoffice/phpword/src/PhpWord/Writer/HTML/Element/
            $path = str_replace('\\','/',realpath(dirname(__FILE__).'/'))."/"; // --- D:/phpstudy_pro/WWW/word
            $path = explode('/vendor/phpoffice/phpword/src/PhpWord/Writer/HTML/Element/',$path)[0]; // 二、調用在類中新增的方法,將圖片存入 D:/phpstudy_pro/WWW/word/public/word_images
            $imageData = $this->element->base64_image_content($imageData, $path.'/public/word_images'); // 三、替換爲html裏要顯示的格式,替換時根據項目的默認路徑靈活修改
            $imgPath = str_replace($path."/","",$imageData); // 原生php版本 // $imgPath = str_replace($path."/public/","",$imageData); // thinkphp版本
            $content .= $this->writeOpening(); // 四、返回
            $content .= "<img border=\"0\" style=\"{$style}\" src=\"{$imgPath}\"/>"; $content .= $this->writeClosing(); } return $content; }
 
四、原生php的demo(框架的demo實在太大了,就不放出來了,你們同理本身改寫下就好)
下載項目部署到服務器上,訪問form.html便可查看效果~
相關文章
相關標籤/搜索