Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force Downloading a PDF file, corrupt file

I've got a problem that has risen many times on SO, but I can't seem to find the solution to mine! I'm trying to deliver a pdf file to the client without it opening in the browser, the file downloads but it is corrupt when I open it and is missing quite a few bytes from the original file. I've tried several such methods for downloading the file but I'll just show you the latest I've used and hopefully get some feedback.

I have also opened the downloaded PDF in a text editor and there are no php errors at the top of it that I can see!

I'm also aware that readfile() is much quicker but for testing purposes I am desperate to get anything working so I used the while(!feof()) approach!

Anyway enough rambling, heres the code (taken from why my downloaded file is alwayes damaged or corrupted?):

$file     = __DIR__ . '/reports/somepdf.pdf';
$basename = basename($file);
$length   = sprintf("%u", filesize($file));

header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $basename . '"');
header('Content-Transfer-Encoding: binary');
header('Connection: Keep-Alive');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . $length);

ob_clean();
set_time_limit(0);
readfile($file);

Also to note was the difference in file size:

Original: 351,873 bytes
Downloaded: 329,163 bytes
like image 495
David C Avatar asked Apr 08 '13 21:04

David C


People also ask

How do I download a corrupted PDF file?

Head to the location where the PDF is saved, right click on the file and select Restore previous versions. Convert the PDF. if you are still having no luck with repairing a damaged PDF, you can extract the information from within, then save it into a Word document.

Why are my PDF failing to download?

Typically, this occurs for one of the following reasons: Your computer is not connected to the Internet, or there is a problem with your Internet settings. Your antivirus software needs to be updated. You may not be connected to the Adobe server.


1 Answers

Make sure you're not running any compression output buffering handlers, such as ob_gzhandler. I had a similar case and I had to disable output buffering for this to work properly

like image 187
periklis Avatar answered Oct 19 '22 11:10

periklis