Reputation: 6802
I'm trying to generate and Download PDF Files. The generation and the storage on the server is working.
In the last step I want to force the download of the generated pdf file.
I'm using the following code:
$filename = "test.pdf";
$filepath = "path/to/file.pdf";
header("Content-type:application/pdf");
header("Content-Disposition:attachment;filename='".$filename."'");
readfile($filepath);
The download itself is working, however the pdf says: Error on loading the PDF-Document
I've tried other solutions with other headers (more detailed) and nothing seems to work... any ideas?
PS: The downloaded file isn't empty (Filesize ~20 KB which should be correct)
Update: The problem only occurs when running it on my local machine. Uploaded to a server it is working...
Upvotes: 1
Views: 2131
Reputation: 11943
If downloading the PDF file directly from the server, without PHP in the way, results in a valid PDF then I would say it's highly likely that PHP is what's corrupting the downloaded file. The most likely cause is output from the error handler, like a notice or warning.
Best way to determine if this is the case is to comment out the readfile
call and leave everything else in place. Then open the resulting file in a text editor and see what the output is, if any. If it is indeed errors from the error handler, you want to go ahead and fix those bugs first.
Additionally, there should be a space between the HTTP header name and value.
header("Content-type: application/pdf");
header("Content-Disposition: attachment;filename='".$filename."'");
and not...
header("Content-type:application/pdf");
header("Content-Disposition:attachment;filename='".$filename."'");
Upvotes: 1