接上一篇phpword生成word文档,如有不明白的问题可以先查看上一篇文章
首先,生成PDF需要先生成word文档,而后通过word文档生成HTML文档,最后才可以通过HTML文档生成PDF文件,详细代码如下。
执行命令安装phpword:
composer require phpoffice/phpword
将word转为HTML然后转为PDF的后端代码如下:
- public function wordToPdf()
- {
- $order_id = request()->get('order_id');
- $sale_order = SaleOrderModel::with(['customer'])->where('id',$order_id)->first();
- $file_name= $sale_order['contract'];//此字段存储的是生成好的word的文件地址
-
- $file = public_path('storage/'.$file_name);
-
- $phpWord = IOFactory::load($file);
-
- $html = IOFactory::createWriter($phpWord ,'HTML');
-
- // 设置Dompdf
- $dompdf = new Dompdf();
-
- // 将Word文档内容转换为HTML
- $html->save(storage_path('app/public/contract/'.$order_id.'.html'));
-
- $html = file_get_contents(base_path().'/public/storage/contract/'.$order_id.'.html');
-
- //这几步是因为复杂的HTML样式不被识别,所以将其替换掉
- $css = <<<HTML
- *{ font-family: simsun, DejaVu Sans, sans-serif;}
- HTML;
-
- $font = "font-family: '宋体';";
- $style = "* {";
- $style_new = "* { word-wrap: break-word;";
- $search = '';
- $html = str_replace($search,$css.'',$html);
- $html = str_replace($font,'',$html);
- $html = str_replace($style,$style_new,$html);
-
- // 加载HTML到Dompdf
- $dompdf->loadHtml($html);
- $dompdf->setPaper('A4', 'portrait');
- // file_put_contents($target, $dompdf->output());
- // 渲染HTML为PDF
- $dompdf->render();
- $pdf_name = $sale_order->customer->name;
- return $dompdf->stream($pdf_name);
-
-
- }
前端的页面样式(建议先查看上一篇文章PHP+laravel 生成word):
- {
- "type": "link",
- 'body':'PDF下载',
- "className" : "pdf_span span",
- "href": "{{admin_url('sale-order/wordToPdf?order_id='.$order_id)}}",
- "style": {
- "margin-left": "80px",
- "margin-top" : "5px",
- "padding" : "3px 12px",
- }
- },
其中需要使用字体文件,下载文字包地址
https://download.csdn.net/download/QiZong__BK/89482065?spm=1001.2014.3001.5503
这样就完成啦