如何将PHP Convertapi HTML转换为PDF而不使用physcal HTML文件

时间:2018-04-25 11:37:01

标签: html string convertapi

我希望转换一个html文档,使用convertAPI通过CURL(即没有物理文件)将其作为字符串($ html)存储到PDF中

我不明白我需要如何将$ 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);
}  
}

谢谢

1 个答案:

答案 0 :(得分:1)

试试这个简短的例子:

$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