如何通过ConvertAPI的CURL接口将字符串HTML转为PDF(无物理文件)
如何用ConvertAPI将HTML字符串直接转换为PDF(无需物理文件)
我明白你看官网示例的时候可能被文件上传的例子绕晕了——其实完全不用把HTML保存到物理文件,直接把字符串传给API就行,我给你写一个完整的可运行示例,再一步步拆解关键要点:
<?php // 你的HTML内容字符串(替换成你实际的内容) $html = '<!DOCTYPE html><html><body><h1>我的测试文档</h1><p>这是通过ConvertAPI直接转换的HTML字符串</p></body></html>'; // API配置参数 $parameters = [ 'Secret' => '你的ConvertAPI密钥', // 记得替换成你自己的密钥 'Html' => $html, // 重点!直接把HTML字符串传这里 // 可选:添加PDF自定义参数,比如页面尺寸、边距 'PageSize' => 'A4', 'MarginBottom' => '15mm' ]; // 封装的ConvertAPI调用函数 function convert_api($src_format, $dst_format, $parameters) { $api_url = "https://v2.convertapi.com/convert/{$src_format}/to/{$dst_format}"; // 初始化CURL $curl = curl_init($api_url); // 设置CURL选项,确保请求正确发送 curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_POST, true); curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($parameters)); curl_setopt($curl, CURLOPT_HTTPHEADER, [ 'Content-Type: application/x-www-form-urlencoded' ]); // 执行请求并获取结果 $response = curl_exec($curl); $http_status = curl_getinfo($curl, CURLINFO_HTTP_CODE); // 检查CURL错误 if (curl_errno($curl)) { throw new Exception('CURL请求出错: ' . curl_error($curl)); } curl_close($curl); // 解析API返回的JSON响应 $result_data = json_decode($response, true); if ($http_status !== 200 || isset($result_data['Error'])) { $error_msg = $result_data['Error']['Message'] ?? '未知错误'; throw new Exception('API转换失败: ' . $error_msg); } // 解码Base64格式的PDF内容并返回 return base64_decode($result_data['Files'][0]['FileData']); } // 调用转换函数并处理结果 try { $pdf_content = convert_api('html', 'pdf', $parameters); // 方案1:直接在浏览器中显示PDF header('Content-Type: application/pdf'); header('Content-Disposition: inline; filename="converted.pdf"'); echo $pdf_content; // 方案2:保存PDF到服务器(如果需要) // file_put_contents('converted.pdf', $pdf_content); } catch (Exception $e) { echo '转换出错: ' . $e->getMessage(); } ?>
关键要点解释:
- 核心参数
Html:这是你最需要注意的——不用处理文件上传,直接把你的$html变量赋值给parameters里的Html字段,API会直接解析这个字符串作为转换源。 - CURL请求配置:用
http_build_query把参数编码成表单格式,配合application/x-www-form-urlencoded头,确保API能正确识别你传递的内容。 - 响应处理:API返回的JSON里,
Files[0]['FileData']是Base64编码的PDF内容,解码后就可以直接输出到浏览器,或者保存成文件。 - 可选配置:你可以根据需求添加更多参数,比如设置页面方向、字体、页眉页脚等,这些都可以在参数数组里直接添加。
之前官网示例可能更多展示文件上传的场景,但针对字符串转PDF的需求,用Html参数就完全足够了,不用纠结文件操作的部分。
内容的提问来源于stack exchange,提问作者Clint
相关产品推荐
相关产品推荐

