composer require phpoffice/phpword
假设咱们的Word名称叫作 iamking.docx
,如图php
空白项目中建立PHP文件,index.php
git
<?php /** * Created by PhpStorm. * User: smallForest<1032817724@qq.com> * Date: 2021/1/6 * Time: 17:44 */ require_once "vendor/autoload.php"; //引入TemplateProcessor use PhpOffice\PhpWord\TemplateProcessor; //实例化, 参数传入模板文件地址 $templateProcessor = new TemplateProcessor('word/iamking.docx'); //替换(设置)变量值,我在测试的时候替换的字符比较长,这里缩短了 $templateProcessor->setValue('kouhao', '我是测试口号!奥利给nice'); $templateProcessor->setValue('date', '2021-10-01'); //保存文件 $templateProcessor->saveAs('word/iamking2.docx');
平时用的最多的也就是Linux中操做,须要安装一个libreoffice服务。本机环境centos7github
yum install libreoffice
假设咱们上一步保存的文件iamking2.docx
在/root/word
中。执行如下命令centos
cd /root/word/ libreoffice --convert-to pdf:writer_pdf_Export iamking2.docx
会在当前目录生成一个同名的PDF文件iamking2.pdf
服务器
通过第二步觉得大功告成,其实否则。生成的PDF中的中文会被识别成小方块,显然不是咱们指望的结果。
错误缘由:Linux服务器缺乏中文字体
解决:进入Mac /System/Library/Fonts
目录,找到这两个字体文件
上传到Linux的/usr/share/fonts/chinese
的目录中composer
cd /usr/share/fonts //缺乏chinese目录须要生成 mkdir chinese //上传字体文件以后,修改权限 chmod 755 -R chinese fc-list
再次执行导出命令,字体就能够了测试
libreoffice是单线程的,多个文件导出的时候要进行加锁排队,否则会出现意外错误
PHP执行脚本,须要考虑好。具体的实现细节本身衡量字体