Hi,

I did a search on web but couldn't really find anything, well anything explained in detail at least ..

How can I make .pdf file downloadable insted of it opening in web browser?

I know that I can rar it , bu I really want to make it downloadable unrared .

Dani AI

Generated

: you can make a PDF download instead of opening in the browser without zipping it. As hinted, the most reliable way is to have the server send a download disposition. Below are practical, tested options, sample snippets, and quick tests.

Client-side (HTML5)

Use the download attribute on an anchor for a simple same-origin solution:

<a href="/files/document.pdf" download>Download PDF</a>

You can add download="name.pdf" to suggest a filename. This is easy but limited (same-origin and browser support). See the download attribute (MDN) for details: download attribute (MDN)

Server-side (recommended)

Serve the file with an HTTP header that forces download. Example PHP:

<?php
$file = '/path/to/document.pdf';
if (is_file($file)) {
  header('Content-Type: application/pdf');
  header('Content-Disposition: attachment; filename="document.pdf"');
  header('Content-Length: ' . filesize($file));
  readfile($file);
  exit;
}
?>

Sanitize any filename input, avoid exposing filesystem paths, and do not readfile() huge files without using X-Sendfile/X-Accel-Redirect or letting the webserver handle the transfer.

Web server configuration

With Apache and mod_headers you can force PDFs to be served as attachments:

<FilesMatch "\.pdf$">
  Header set Content-Disposition "attachment"
</FilesMatch>

Enable mod_headers and test headers with curl:

curl -I https://example.com/files/document.pdf

Look for Content-Disposition: attachment; filename="document.pdf".

Notes and troubleshooting

  • Correct Content-Type plus Content-Disposition: attachment is the robust approach; some client plugins or user settings may still open PDFs in a viewer.
  • If using S3 or a CDN, set the object metadata Content-Disposition or use the provider's response-query parameters. See Amazon S3 docs: Using Content-Disposition with S3
  • For long files, prefer server-native file serving (X-Sendfile/X-Accel-Redirect) to avoid PHP memory/time limits.

References above explain edge cases and browser limits; the server-side header is the most dependable method.

Recommended Answers

All 2 Replies

Thanks, will give it a try!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.