用我現在最常使用的php框架fastadmin舉例子,當然thinkphp或者原生php也是同樣的原理,大家理解思路就好了、
環境:fastadmin,summernote編輯器 【summernote的居中功能在段落里,且不會吃掉section標簽,加上匯入word功能之后,簡直完美~】 按照國際慣例先放效果圖
github上的demo里我還沒有換圖示,不過fastadmin里的是換了的,效果如下:
1、thinkphp使用composer安裝phpword插件(這個插件能夠把word轉為html)
composer require phpoffice/phpword
安裝完成之后的檔案在vender目錄下

2、打開require統一管理后臺插件的js

引入我們需要的ajaxfileupload.js插件(這個插件允許檔案通過ajax上傳到服務器,而不是form表單)

'ajaxfileupload':'../libs/ajaxfileupload/ajaxfileupload',
3、以新增新聞的編輯器為例,打開

在開頭載入需要的組件

define(['jquery', 'bootstrap', 'backend', 'table', 'form','summernote','layer','ajaxfileupload'], function ($, undefined, Backend, Table, Form,summernote,layer,ajaxfileupload) {
然后修改add方法
add: function () {
Controller.api.bindevent();
var imageButton = function (context) {
var ui = $.summernote.ui;
var button = ui.button({
contents: '<i />',
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 />',
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 />',
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="https://www.cnblogs.com/chenyingying0/p/上傳" 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);
}
});
});
},
4、修改控制器

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;
}
5、記得public目錄下創建一個words檔案夾,用來存盤word和html檔案
----------------------------------------------------------------------------------------
實踐程序中發現base64格式的代碼太長、太占空間,于是決定將base64格式的圖片轉為普通格式的圖片,存入服務器
1、修改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;
}
}
2、提前創建好存放圖片的檔案夾
D:/phpstudy_pro/WWW/word/public/word_images
3、修改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;
// 1、獲取到專案根目錄
// ---- 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];
// 2、呼叫在類中新增的方法,將圖片存入 D:/phpstudy_pro/WWW/word/public/word_images
$imageData = $this->element->base64_image_content($imageData, $path.'/public/word_images');
// 3、替換為html里要顯示的格式,替換時根據專案的默認路徑靈活修改
$imgPath = str_replace($path."/","",$imageData); // 原生php版本
// $imgPath = str_replace($path."/public/","",$imageData); // thinkphp版本
$content .= $this->writeOpening();
// 4、回傳
$content .= "<img border=\"0\" style=\"{$style}\" src=https://www.cnblogs.com/"{$imgPath}\"/>";
$content .= $this->writeClosing();
}
return $content;
}
4、原生php的demo(框架的demo實在太大了,就不放出來了,大家同理自己改寫下就好)
github地址:https://github.com/chenyingying1016/import_word_to_html.git
下載專案部署到服務器上,訪問form.html即可查看效果~
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/254681.html
標籤:PHP
下一篇:PHP的并發處理
