Prevent PDFs from opening in browser window

Is there code to prevent PDF’s or any other file from opening in the browser window?

How can I code it so it makes the user download it into their hard drive?

Not with HTML, but you can do it by setting the HTTP header using a scripting language:

$filename = "document.pdf";
$path = "files/pdf/";

if(file_exists($path.$filename)) {
 header("Content-Type: application/pdf");
 header("Content-Disposition: attachment; filename='".$filename."'");
 readfile($path.$filename);
}
else {
 printf("Could not read file %s located at %s", $filename, $path);
}

Be careful with which files you allow in this function, though, as this function will download any file without parsing it, including PHP files with your database password, etc.

I wouldn’t appreciate any site forcing me to do this.

Neither would I. I would expect to open the pdf in the browser then if whatever the pdf is about is of interest save it to a local drive from there. I would not want to have to go through two steps to open a pdf when i could view it in one step.

It would only make sense to force the PDF for download when the link to the PDF is on a page where the exact same information is available on the web page and the only reason for the PDF is to allow the person to save a copy for later reference. Then forcing the download saves the step of having the PDF open in the browser before you hit the save button. You’d need to make it clear that the PDF contains the same info as the web page the person just read though so that there is no reason why they need to open the PDF now.

I guess it’s a matter of taste. I for one prefer to be prompted to download the document, as I may not need it immediately. Opening the document in the browser will slow down my machine, especially if I open a lot of documents at the same time. The download prompt will also give the option to open the document, if the user prefers this.