Jagan K
Jagan K

Reputation: 1057

Making PHP curl request to Download PDF using API url

The following url will download a PDF of any given url if it's run on browser directly. http://htmltopdfapi.com/querybuilder/api.php?url=http%3A%2F%2Fwww.google.com%2F

I need to download the file using curl within my server itself.

I am using CURL request to do this.

$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;

The above code downloads the pdf, but the pdf is corrupted, How to make it work?

Upvotes: 2

Views: 17576

Answers (2)

Neal
Neal

Reputation: 286

Your PDF is corrupted because it also contains the HTTP headers you got from the API. You don't seem to need the headers, so you can remove this line:

curl_setopt($CurlConnect, CURLOPT_HEADER, true);

Also note here that adding Content-Disposition: attachment will make the browser download the file rather than try to render it.

You should also close your cURL session. See the docs for more details.

Upvotes: 0

slapyo
slapyo

Reputation: 2991

<?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);

Upvotes: 2

Related Questions