«

php+wkhtmltoimage 将html转成图片

时间:2025-2-28 16:30     作者:杨佳乐     分类: PHP


1.安装wkhtmltopdf
ubuntu 安装
sudo apt-get install wkhtmltopdf
centos 安装
sudo yum install wkhtmltopdf

2.php中使用thinkphp-template模板组件

$res = ThinkPHP::render('mobile',['html'=>$html]);

        $filename = runtime_path().'/html/'.time().mt_rand(1,999).'.html';
        file_put_contents($filename, $res);

        $tempHtmlFile = $filename;

        // 生成图像输出文件路径
        $outputImageFile = runtime_path().'/html/res.png';

        // 使用 wkhtmltoimage 命令行工具生成图像
        //quality 质量 1-100
        //width 宽度
        //-disable-smart-width 禁用宽度自动调整
        // --zoom 0.8 缩小分辨率
        $command = "wkhtmltoimage --width 700 --quality 75 --disable-smart-width $tempHtmlFile $outputImageFile";
        //exec($command);
        exec($command, $output, $status);
        if ($status == 0) {
            echo "生成成功!";
        } else {
            echo "生成失败!状态码: " . $status;
            print_r($output);  // 查看详细的错误输出
        }

        if (file_exists($tempHtmlFile)) {
            unlink($tempHtmlFile);  // 删除临时文件
            echo "临时文件已删除";
        } else {
            echo "临时文件不存在,无法删除";
        }