0

I am trying to download a pdf file using php . I can download text file and image and My PHP Code :

header("Content-Type: application/octet-stream");

$file = $_GET["file"] .".pdf";
header("Content-Disposition: attachment; filename=" . urlencode($file));    
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Type: application/pdf");   // pdf might change to another format eg. doc,docx
header("Content-Description: File Transfer");            
header("Content-Length: " . filesize($file));
flush(); // this doesn't really matter.
$fp = fopen($file, "r");
while (!feof($fp))
{
echo fread($fp, 65536);
flush(); // this is essential for large downloads
} 
fclose($fp); 

and here is the HTML

part :

<a href="download.php?file=abc">Download CV</a>

In my case I am able to download the PDF file and it's showing the memory size also but when I opened it show me error like :

Failed to load PDF Document

I am not getting any error and I tried to change the memory limits and all but not working . Any help will be really appreciated .

EDIT :

I need to download all the file format with some simple changes in my code . example :

 header("Content-Type: application/pdf");   // pdf might change to another format eg. doc,docx 

I don't want to save the PDF file which is displayed in the browser because in the case of other formats I cannot directly save from browser .

When I tried to open file from the downloads folder it shows an error like :

Adobe reader could not open the file name abc.pdf because it's either not a supported file type or because the file has been damaged

Vishnu R Nair
  • 335
  • 2
  • 17
  • if I may ask, why do you need this header header("Content-Type: application/download"); – Satya Sep 07 '15 at 05:51
  • possible duplicate of [Chrome has "Failed to load PDF document" error message on inline PDFs](http://stackoverflow.com/questions/5670785/chrome-has-failed-to-load-pdf-document-error-message-on-inline-pdfs) – Saty Sep 07 '15 at 05:54
  • @Saty no it does not solve my problem exactly . It show the contents on the browser even though I can save because it's PDF file . But not with any other formats – Vishnu R Nair Sep 07 '15 at 06:24
  • try solution here https://stackoverflow.com/questions/45101160/how-to-make-mpdf-6-1-work-with-php-7-1-5 – Montaser El-sawy May 06 '20 at 00:31

1 Answers1

0

Can you try this?

Change your

echo fread($fp, 65536);

to

echo fread($fp, filesize($file));

My guess is the length of the pdf file is different on what you specified.

kdlcruz
  • 1,368
  • 13
  • 20