如何在没有物理 HTML 文件的情况下 PHP 将 HTML 转换为 PDF

How to PHP Convertapi HTML to PDF without physcal HTML file

我希望通过 CURL 使用 convertAPI(即没有物理文件)

我不明白我如何需要 post 将 $html 转换为 API,我正在查看 convertapi 网页上的示例,但我不知道好像能看懂。

示例粘贴在下方。

$html = '<hmtl file contents>' ;

$parameters = array(
    'Secret' => 'X?X?X?X?X?X?X',
);


function convert_api($src_format, $dst_format, $files, $parameters) {
$parameters = array_change_key_case($parameters);
$auth_param = array_key_exists('secret', $parameters) ? 'secret='.$parameters['secret'] : 'token='.$parameters['token'];
$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl,  CURLOPT_SSL_VERIFYPEER , false);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_URL, "https://v2.convertapi.com/{$src_format}/to/{$dst_format}?{$auth_param}");

if (is_array($files)) {
    foreach ($files as $index=>$file) {
        $parameters["files[$index]"] = file_exists($file) ? new CurlFile($file) : $file;
    }    
} else {
        $parameters['file'] = file_exists($files) ? new CurlFile($files) : $files;
}    

curl_setopt($curl, CURLOPT_POSTFIELDS, $parameters);
$response = curl_exec($curl);
$httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
$error = curl_error($curl);
curl_close($curl);
if ($response && $httpcode >= 200 && $httpcode <= 299) {
    return json_decode($response);
} else {
    throw new Exception($error . $response, $httpcode);
}  
}

谢谢

试试这个简短的例子:

$secret = 'XXXXXXXXXX';

$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_BINARYTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/octet-stream', 'Accept: application/octet-stream', 'Content-Disposition: attachment; filename="file.html"'));
curl_setopt($curl, CURLOPT_URL, "https://v2.convertapi.com/html/to/pdf?secret=".$secret);
curl_setopt($curl, CURLOPT_POSTFIELDS, '<!doctype html><html lang=en><head><meta charset=utf-8><title>Conversion test</title></head><body>This is html body</body></html>');
$result = curl_exec($curl);
if (curl_getinfo($curl, CURLINFO_HTTP_CODE) == 200) {
    file_put_contents("result.pdf", $result);
} else {
    print("Server returned error:\n".$result."\n");
}

可以在以下位置找到更多示例:https://repl.it/@ConvertAPI