使用php调用python文件,执行切割pdf文件

应用场景,使用php执行python文件,进行pdf文件切割

代码如下:

public function slicePdf(Request $request){
        // 要传递给 Python 脚本的参数
        $inputPath = "input.pdf"; //需要切割的文件目录
        $outputPath = "output.pdf"; //切割完成以后得新文件
        $startPage = 1; //开始页数
        $endPage = 30; //结束页数

        // 构建要执行的命令
        $command = "python D:/py_project/tools/SlicePdfFile.py $inputPath $outputPath $startPage $endPage";

        // 执行命令并获取输出
        $output = shell_exec($command);
        dd($output);
    }

也可以调用一个本地python的flask接口:

public function slicePdf(){
        // 创建 GuzzleHttp 客户端
        $client = new Client();
        $inputPath = "D:\py_project/tools/2016_PDF.pdf";
        $outputPath = "D:\py_project/tools/output.pdf";
        $startPage = 1;
        $endPage = 30;
        try {
            // 发送 POST 请求到本地接口
            $response = $client->post('http://localhost:8000/api/split_pdf', [
                'form_params' => [
                    'input_path' => $inputPath,
                    'output_path' => $outputPath,
                    'start_page' => $startPage,
                    'end_page' => $endPage,
                ]
            ]);
            // 获取响应数据
            $responseData = json_decode($response->getBody(), true);
            return $this->success('ok',$responseData);
        } catch (\Exception $e) {
            // 处理异常
            Log::error($e->getMessage());
            return $this->failure('调用失败');
        }
    }
posted @ 2023-07-26 17:55  八戒vs  阅读(42)  评论(0编辑  收藏  举报