使用PhpWord+DomPDF转换Docx至PDF时样式丢失、阿拉伯文乱码问题
Docx转PDF:样式丢失+阿拉伯文显示乱码的解决方案
我用PhpWord结合DomPDF实现Docx转PDF功能,转换能完成,但出现两个问题:
- 原Docx文档的样式完全丢失
- 阿拉伯文字符全部显示为'????'
实现代码
public function attr(Request $request) { /* Set the PDF Engine Renderer Path */ $domPdfPath = base_path('vendor/dompdf/dompdf'); \PhpOffice\PhpWord\Settings::setPdfRendererPath($domPdfPath); \PhpOffice\PhpWord\Settings::setPdfRendererName('DomPDF'); $template = new TemplateProcessor(storage_path('app/public/docs/AR.docx')); // Get the form data $title = $request->input('title'); // Replace placeholders with form data $template->setValue('title', $title); /*@ Save Temporary Word File With New Name */ $name = uniqid(); $saveDocPath = storage_path('app/public/docs/AR_'.$name.'.docx'); $template->saveAs($saveDocPath); // Load temporarily create word file $Content = \PhpOffice\PhpWord\IOFactory::load($saveDocPath); //Save it into PDF $savePdfPath = storage_path('app/public/pdfs/attr/AR_'.$name.'.pdf'); /*@ If already PDF exists then delete it */ if ( file_exists($savePdfPath) ) { unlink($savePdfPath); } //Save it into PDF $PDFWriter = \PhpOffice\PhpWord\IOFactory::createWriter($Content,'PDF'); $PDFWriter->save($savePdfPath); echo 'File has been successfully converted'; /*@ Remove temporarily created word file */ if ( file_exists($saveDocPath) ) { unlink($saveDocPath); } return response()->download($savePdfPath, 'AR.pdf'); }
转换效果说明
- 转换前:Docx文档中阿拉伯文正常显示,段落、字体等样式排版完整
- 转换后:PDF里阿拉伯文全部变成'????',原有的文档样式(如字体大小、段落间距、对齐方式)完全丢失
解决方案
1. 解决阿拉伯文乱码问题
DomPDF对RTL(从右到左)语言支持有限,且默认字体不包含阿拉伯文字符,需要做以下调整:
- 添加阿拉伯字体:下载支持阿拉伯文的字体(如Noto Naskh Arabic),将字体文件(.ttf)放到
vendor/dompdf/dompdf/lib/fonts目录,然后在代码中指定默认字体:$Content->setDefaultFontName('Noto Naskh Arabic'); - 开启RTL渲染:在创建PDFWriter后添加RTL配置:
$dompdf = $PDFWriter->getRenderer(); $dompdf->set_option('is_rtl', true);
2. 解决样式丢失问题
PhpWord结合DomPDF对复杂Docx样式的解析能力不足,推荐两种优化方案:
- 替换PDF渲染器:改用MPDF或TCPDF,这两个工具对Docx样式和RTL语言的支持更完善。以MPDF为例:
- 安装依赖:
composer require mpdf/mpdf - 修改代码中的PDF渲染配置:
\PhpOffice\PhpWord\Settings::setPdfRendererName('MPDF'); \PhpOffice\PhpWord\Settings::setPdfRendererPath(base_path('vendor/mpdf/mpdf'));
- 安装依赖:
- 检查模板替换逻辑:确保TemplateProcessor替换占位符时没有破坏原样式,比如占位符所在的段落、字体样式要和原文本一致;复杂模板可使用
setBlock或cloneBlock方法保持样式。
内容的提问来源于stack exchange,提问作者NOURDDINE BENYAHYA
相关产品推荐
相关产品推荐

