phpword生成PDF

接上一篇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 = '</style>';
        $html = str_replace($search,$css.'</style>',$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

这样就完成啦

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值