使用api2pdf生成PDF后,如何添加代码保存到服务器指定文件夹?
解决方案:同时保存PDF到共享服务器+浏览器下载
核心修改逻辑
- 新增共享服务器的目标路径配置
- 先将PDF内容写入服务器指定文件夹,再输出给浏览器完成下载
修改后的完整代码
$api_key = ''; $filename = 'Agreement.pdf'; // 替换为你的共享服务器实际路径,必须确保PHP运行用户对该路径有写入权限 $server_save_path = '/mnt/shared-storage/pdf-archives/' . $filename; $url = '../agreement-buyer.php'; $postData = json_encode(array( 'url' => $url, 'options' => $options )); $headers = array( 'Content-Type: application/json', 'Authorization: ' . $api_key ); $curl = curl_init(); curl_setopt_array($curl, array( CURLOPT_URL => $endpoint, CURLOPT_RETURNTRANSFER => true, CURLOPT_POST => true, CURLOPT_POSTFIELDS => $postData, CURLOPT_HTTPHEADER => $headers )); $response = curl_exec($curl); if (!curl_errno($curl)) { $http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE); if ($http_code === 200) { $response_obj = json_decode($response); $pdf_url = $response_obj->FileUrl; // 步骤1:将PDF保存到共享服务器指定路径 $pdf_content = file_get_contents($pdf_url); if (!$pdf_content) { echo '无法获取PDF文件内容'; exit; } if (!file_put_contents($server_save_path, $pdf_content)) { echo '无法将PDF保存到服务器路径'; exit; } // 步骤2:输出PDF给浏览器下载 header('Content-Type: application/pdf'); header('Content-Disposition: attachment; filename="' . $filename . '"'); echo $pdf_content; } else { echo '生成PDF失败,HTTP状态码: ' . $http_code; exit; } } else { echo '生成PDF出错: ' . curl_error($curl); exit; } curl_close($curl); unset($_GET); unset($_POST);
关键注意事项
- 路径权限:
$server_save_path需替换为真实的共享服务器文件夹路径,若为网络共享目录,需先确认服务器已挂载该目录,且PHP运行用户拥有该路径的写入权限。 - 替代保存方式:如果服务器禁用了
file_get_contents,可改用curl方式保存文件,替换步骤1的代码:$ch = curl_init($pdf_url); $fp = fopen($server_save_path, 'wb'); curl_setopt($ch, CURLOPT_FILE, $fp); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); $save_success = curl_exec($ch); curl_close($ch); fclose($fp); if (!$save_success) { echo '保存PDF到服务器失败'; exit; }
内容的提问来源于stack exchange,提问作者Paul Holness
相关产品推荐
相关产品推荐

