PHP 实现linux环境下使用PhpWord读取修改word模板,并生成PDF
tp5安装PhpWord
-
下载phpword
github -
下载下来后src里的将phpword文件夹拖入tp5的extend的PhpOffice文件夹下
使用PhpWord读取word模板
- 打开一个docx模板,在里面设置占位符:${占位符}
- 创建方法,读取修改docx模板
<?php
namespace app\api\controller;
use think\Controller;
use think\Request;
use Exception;
use PhpOffice\PhpWord\TemplateProcessor;
class Test extends Controller
{
protected $request;
public function _initialize()
{
$this->request = Request::instance();
}
/**
* @api {get} /api/test/test 测试
* @apiName test
* @apiGroup Test
*/
public function test()
{
try {
// 模板位置
$docxPath = ROOT_PATH . 'public' . DS . 'file' . DS . '8.docx';
// 图片位置
$imgPath = ROOT_PATH . 'public' . DS . 'img' . DS . 'index1_QR.png';
// 生成文件的位置
$fileName = ROOT_PATH . 'public' . DS . 'file' . DS . 'test.docx';
// 读取模板
$templateProcessor = new TemplateProcessor($docxPath);
// 替换占位符,把占位符替换成自己的内容
// 替换文本内容
$templateProcessor->setValue('1', 'hello,world!');
// 替换图片
$templateProcessor->setImageValue('2', $imgPath);
// 另存docx文件,只能保存为docx文件
$templateProcessor->saveAs($fileName);
return;
} catch (Exception $e) {
return $e->getMessage();
}
}
}
- 执行方法,打开生成的docx
更多编辑模板的方法:
PhpWord官方文档
ps:修改占位符的方法
打开TemplateProcessor.php
,找到ensureMacroCompleted($macro)
方法
生成PDF
这里需要用到一个强大的linux工具 libreoffice
直接执行下面的代码就可以(第一个安装好就ok了,后面两个安装的时候可能会报错,但是只要第一个安装好了,其实没什么大的影响)
1 yum install libreoffice
2 yum install libreoffice-headless
3 yum -y install libreoffice-langpack-zh-Han*
安装完成libreoffice后,我们使用下面的代码来测试一下是否安装成功:
soffice --headless --invisible --convert-to pdf 1.docx
(如果是 ppt 转图片的话只要把后面的 docx 文件 换成 pptx 文件即可)
如果在执行命令的目录下,生成了一个与word同名的pdf文件,即说明libreioffice安装成功了
其余libreioffice可以自行查看官方文档
libreioffice官方文档
php执行exec()方法
exec("soffice --headless --invisible --convert-to pdf 1.docx");
执行失败则需要修改php.ini
开放exec()
方法
至此整个流程已经结束,以下是完整代码
<?php
namespace app\api\controller;
use think\Controller;
use think\Request;
use Exception;
use PhpOffice\PhpWord\TemplateProcessor;
class Test extends Controller
{
protected $request;
public function _initialize()
{
$this->request = Request::instance();
}
/**
* @api {get} /api/test/test 测试
* @apiName test
* @apiGroup Test
*/
public function test()
{
try {
// 模板位置
$docxPath = ROOT_PATH . 'public' . DS . 'file' . DS . '8.docx';
// 图片位置
$imgPath = ROOT_PATH . 'public' . DS . 'img' . DS . 'test.png';
// 生成docx的位置
$fileName = ROOT_PATH . 'public' . DS . 'file' . DS . 'test.docx';
// 读取模板
$templateProcessor = new TemplateProcessor($docxPath);
// 替换占位符,把占位符替换成自己的内容
// 替换文本内容
return $templateProcessor->setValue('1', 'hello,world!');
// 替换图片
$templateProcessor->setImageValue('2', $imgPath);
// 另存docx文件,只能保存为docx文件
$templateProcessor->saveAs($fileName);
// 生成pdf的文职
$pdfPath = ROOT_PATH . 'public' . DS . 'img' . DS . 'test.pdf';
// 执行linux命令
exec("soffice --headless --invisible --convert-to pdf $fileName --outdir $pdfPath");
return;
} catch (Exception $e) {
return $e->getMessage();
}
}
}