如果直接在浏览器上运行,以下网址将下载任何给定网址的PDF。 http://htmltopdfapi.com/querybuilder/api.php?url=http%3A%2F%2Fwww.google.com%2F
我需要在服务器本身内使用curl下载文件。
我正在使用CURL请求来执行此操作。
$CurlConnect = curl_init();
$link = urlencode("https://www.google.com");
$source = "http://htmltopdfapi.com/querybuilder/api.php?url=$link";
curl_setopt($CurlConnect, CURLOPT_URL, $source);
curl_setopt($CurlConnect, CURLOPT_HEADER, true);
curl_setopt($CurlConnect, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($CurlConnect, CURLOPT_NOBODY, true);
curl_setopt($CurlConnect, CURLOPT_TIMEOUT, 10);
curl_setopt($CurlConnect, CURLOPT_SSLVERSION,3);
$Result = curl_exec($CurlConnect);
header('Cache-Control: public');
header('Content-type: application/pdf');
header('Content-Disposition: attachment; filename="new.pdf"');
header('Content-Length: '.strlen($Result));
echo $Result;
以上代码下载pdf,但pdf已损坏,如何使其正常工作?
答案 0 :(得分:0)
<?php
$ch = curl_init();
$link = urlencode("https://www.google.com");
$source = "http://htmltopdfapi.com/querybuilder/api.php?url=$link";
curl_setopt($ch, CURLOPT_URL, $source);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
curl_close($ch);
$destination = dirname(__FILE__) . '/file.pdf';
$file = fopen($destination, "w+");
fputs($file, $data);
fclose($file);
$filename = 'google.pdf';
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$filename");
header("Content-Type: application/pdf");
header("Content-Transfer-Encoding: binary");
readfile($destination);
答案 1 :(得分:0)
您的PDF已损坏,因为它还包含您从API获得的HTTP标头。您似乎不需要标题,因此您可以删除此行:
curl_setopt($CurlConnect, CURLOPT_HEADER, true);
另请注意,添加Content-Disposition: attachment
会使浏览器下载文件而不是尝试渲染它。
您还应该关闭cURL会话。有关详细信息,请参阅the docs。