MPDF类 生成pdf, PHPword 编辑word并生成新word

颛孙沈义
2023-12-01

**MPDF类 生成pdf, PHPword 编辑word并生成新word

TP,Yii 都适用
@引用 mpdf5.0以上 这里我使用的使MPDF53
composer 下载phpword
composer require phpoffice/phpword

项目场景:

自动生成word,pdf 文件
include 'MPDF53/mpdf.php';
require_once 'vendor/autoload.php';//引入

$demoDoc = '1.docx';//模板docx文件

$doc = new \PhpOffice\PhpWord\TemplateProcessor($demoDoc);
$username = '名字';
$phone = '130123456789';
$age = '32岁';

$doc->setValue('name','小宋');
$doc->setValue('phone',$phone);
$doc->setValue('content',' ');

$newDoc = $phone.'.docx';//生成的word文件
$doc->saveAs($newDoc);//保存

$newPdf = $phone.'.pdf';//生成pdf文件
\PhpOffice\PhpWord\Settings::setPdfRendererName(\PhpOffice\PhpWord\Settings::PDF_RENDERER_DOMPDF);
\PhpOffice\PhpWord\Settings::setPdfRendererPath('.');
$pdf = \PhpOffice\PhpWord\IOFactory::load($newDoc);
$xmlWriter = \PhpOffice\PhpWord\IOFactory::createWriter($pdf, 'PDF');
// $html = $xmlWriter->getContent();//获取word内容到HTML
// echo $html;
//实例化mpdf
$mpdf=new Mpdf('utf-8','A4','','宋体',10,10,10,10);

//设置字体,解决中文乱码
$mpdf->useAdobeCJK = true;
$mpdf->SetAutoFont(AUTOFONT_ALL);

//获取要生成的静态文件
// $html=file_get_contents('template.html');
 
// echo $html;
$html = $xmlWriter->getContent();//获取word内容到HTML

//设置pdf显示方式
$mpdf->SetDisplayMode('fullpage');
 
//设置pdf的尺寸为270mm*397mm
//$mpdf->WriteHTML('<pagebreak sheet-size="270mm 397mm" />');
 
//创建pdf文件
$mpdf->WriteHTML($html);
 
//删除pdf第一页(由于设置pdf尺寸导致多出了一页)
//$mpdf->DeletePages(1,1);
 
//输出pdf
$mpdf->Output('24.pdf');
 
exit;


 类似资料: