dcat-admin 实现 phpword 读取内容

dcat-admin 实现 phpword 读取内容

Laravel 1年前 813 0

最近有个需求,运营太懒了不想在富文本里面编辑,直接给个word 自动处理。研究了一下并用 laravel,dcat-admin 后台实现,下面附下代码:

先安装 phpword :

composer require phpoffice/phpword

后台代码:

$form->tab('Basic Info', function(Form $form){
                $form->file('word')->autoUpload();
                $form->ignore('word');
            })->tab('Content', function(Form $form){
                $form->editor('body')->imageDirectory('editor/images/tutorials')->width(10, 1);
            })->saving(function (Form $form) {
                if(request('word')){
                    $file = request('word');
                    $sections = \PhpOffice\PhpWord\IOFactory::load(public_path('uploads/').$file)->getSections();
                    $html = '';
                    //循环所有元素
                    foreach ($sections as $section) {
                        foreach ($section->getElements() as $ele1) {
                            if ($ele1 instanceof \PhpOffice\PhpWord\Element\TextRun) {
                                foreach ($ele1->getElements() as $ele2) {
                                    if ($ele2 instanceof \PhpOffice\PhpWord\Element\Text) {
                                        $html .= mb_convert_encoding($ele2->getText(), 'GBK', 'UTF-8');
                                    } elseif ($ele2 instanceof \PhpOffice\PhpWord\Element\Image) {
                                        $imageDataTmp = $ele2->getImageStringData(true);
                                        $imageType = $ele2->getImageType() ? : 'image/jpg';
                                        $imageData = 'data:' . $imageType . ';base64,' . str_replace(array("\r\n", "\r", "\n"), "", $imageDataTmp);

                                        $imageSrc = './uploads/editor/images/tutorials/' . md5($ele2->getSource()) . '.' . $ele2->getImageExtension();
                                        file_put_contents($imageSrc, base64_decode(explode(',',$imageData)[1]));
                                        $filePath = config('app.url')."/uploads/editor/images/tutorials/" . md5($ele2->getSource()) . '.' . $ele2->getImageExtension();
                                        $html .= "<img src=$filePath style='width:100%;height:auto' />";
                                    }
                                }
                            }
                        }
                    }
                    $html = mb_convert_encoding($html, 'UTF-8', 'GBK');
                    $form->body = $html;
                }
            });

可能出现的问题:

  1. 文件类型问题,word模板文件另存为其他格式。如:docx
  2. 检查 php 是否有权限打开文件
  3. 检查 php 是否有操作 tmp 系统缓存文件的权限

原文: http://yiqiao.me/articles/34/dcat-admin-implements-phpword-reading-content

版权声明: 自由转载-非商用-非衍生-保持署名 (创意共享3.0许可证)