Laravel、thinkPHP框架需要先安装PHPword,需要用PHPword扩展将word转化成html。该插件主要由两部分组成:编辑器上传word插件和文档转换功能代码,最重要的是文档转换代码文件,需要稍作修改才可以使用。
网页效果
具体部署步骤如下:
1、下载WordConvertHtml插件
下载地址:word文档导入百度编辑器word插件,支持带图片文档导入_WPS编辑器-PHP文档类资源-CSDN下载
将WordConvertHtml目录放入百度编辑器目录下,如:/public/vendor/ueditor/plugin
2、在引用百度编辑器的页面引用插件路径
<script type="text/javascript" charset="utf-8" src="/public/vendor/ueditor/plugin/WordConvertHtml/wordConvertDialog.js"></script>
3、添加文档转换代码文件
将WordConvertController.php添加到项目对应的目录,该文件主要完成:word转成html,保存图片到本地,并返回带本地图片路径的html代码。
需要修改文件保存路径
Laravel框架示例代码:
<?php
namespace App\Http\Controllers;
use PhpOffice\PhpWord\IOFactory;
class WordConvertController {
public $extensionArray = ['docx', 'zip']; // 允许上传的文件类型
public $fileMaxSize = 0; // 文件大小限制,单位:字节,0不限。
public function index() {
$file = request()->file('file');
// 文件限制
if (!$file->isValid() || !in_array($file->extension(), $this->extensionArray)) {
return response()->json(['wordTitle' => '-1', 'wordContent' => '无效文件']);
}
if ($this->fileMaxSize && $file->getSize() > $this->fileMaxSize) {
return response()->json(['wordTitle' => '-1', 'wordContent' => '文件大小超过限制']);
}
$phpWord = IOFactory::load($file);
$html = '';
foreach ($phpWord->getSections() as $section) {
foreach ($section->getElements() as $ele1) {
$paragraphStyle = $ele1->getParagraphStyle();
if ($paragraphStyle) {
$html .= '<p style="text-align:'. $paragraphStyle->getAlignment() .';text-indent:20px;">';
} else {
$html .= '<p>';
}
if ($ele1 instanceof \PhpOffice\PhpWord\Element\TextRun) {
foreach ($ele1->getElements() as $ele2) {
if ($ele2 instanceof \PhpOffice\PhpWord\Element\Text) {
$style = $ele2->getFontStyle();
$fontFamily = mb_convert_encoding($style->getName(), 'GBK', 'UTF-8');
$fontSize = $style->getSize();
$isBold = $style->isBold();
$styleString = '';
$fontFamily && $styleString .= "font-family:{$fontFamily};";
$fontSize && $styleString .= "font-size:{$fontSize}px;";
$isBold && $styleString .= "font-weight:bold;";
$html .= sprintf('<span style="%s">%s</span>', $styleString, mb_convert_encoding($ele2->getText(), 'GBK', 'UTF-8'));
} elseif ($ele2 instanceof \PhpOffice\PhpWord\Element\Image) {
$savePath = '/upload/';
$dir = date('Ymd');
$path = public_path() . $savePath . $dir . "/";
if (!file_exists($path)) {
mkdir($path, 0700);
}
$save_src = $path . md5($ele2->getSource()) . '.' . $ele2->getImageExtension();
$image_src = $savePath . $dir . '/' . md5($ele2->getSource()) . '.' . $ele2->getImageExtension();
$imageData = $ele2->getImageStringData(true);
file_put_contents($save_src, base64_decode($imageData));
$html .= '<img src="'. $image_src .'" style="max-width:800px;">';
}
}
}
$html .= '</p>';
}
}
$data = [];
$data['wordTitle'] = $file->getClientOriginalName();
$data['wordContent'] = mb_convert_encoding($html, 'UTF-8', 'GBK');
return response()->json($data);
}
}
ThinkPHP框架示例代码:
待补充……
4、修改插件文件上传form表单请求地址
修改WordConvertHtml/wordConvertDialogPage.html第40行