(HTML) Download a PDF file instead of opening them in browser when clicked

JavascriptHtml

Javascript Problem Overview


I was wondering how to make a PDF file link downloadable instead of opening them in the browser? How is this done in html? (I'd assume it's done via javascript or something).

Javascript Solutions


Solution 1 - Javascript

Solution 2 - Javascript

This is only possible with setting a http response header by the server side code. Namely;

Content-Disposition: attachment; filename=fname.ext

Solution 3 - Javascript

There is now the HTML 5 download attribute that can handle this.

I agree, and think Sarim's answer is good (it probably should be the chosen answer if the OP ever returns). However, this answer is still the reliable way to handle it (as Yiğit Yener's answer points out and--oddly--people agree with). While the download attribute has gained support, it's still spotty:

http://caniuse.com/#feat=download

Solution 4 - Javascript

you will need to use a PHP script (or an other server side language for this)

<?php
// We'll be outputting a PDF
header('Content-type: application/pdf');

// It will be called downloaded.pdf
header('Content-Disposition: attachment; filename="downloaded.pdf"');

// The PDF source is in original.pdf
readfile('original.pdf');
?>

and use httacces to redirect (rewrite) to the PHP file instead of the pdf

Solution 5 - Javascript

You can use

Response.AddHeader("Content-disposition", "attachment; filename=" + Name);

Check out this example:

http://www.codeproject.com/KB/aspnet/textfile.aspx

This goes for ASP.NET. I am sure you can find similar solutions in all other server side languages. However there's no javascript solution to the best of my knowledge.

Solution 6 - Javascript

When you want to direct download any image or pdf file from browser instead on opening it in new tab then in javascript you should set value to download attribute of create dynamic link

    var path= "your file path will be here"; 
    var save = document.createElement('a');  
    save.href = filePath; 
    save.download = "Your file name here"; 
    save.target = '_blank'; 
    var event = document.createEvent('Event');
    event.initEvent('click', true, true); 
    save.dispatchEvent(event);
   (window.URL || window.webkitURL).revokeObjectURL(save.href);

For new Chrome update some time event is not working. for that following code will be use

  var path= "your file path will be here"; 
    var save = document.createElement('a');  
    save.href = filePath; 
    save.download = "Your file name here"; 
    save.target = '_blank'; 
    document.body.appendChild(save);
    save.click();
    document.body.removeChild(save);

Appending child and removing child is useful for Firefox, Internet explorer browser only. On chrome it will work without appending and removing child

Solution 7 - Javascript

Without html5 attribute one can achieve this by using php:

Create php file named download.php with this code:

<?php
ob_start();
$file = "yourPDF.pdf"

if (file_exists($file)) 
{
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename='.basename($file));
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    ob_clean();
    flush();
    readfile($file);
    exit();
}

Now if you want to automatically start downloading pdf write this javascript:

<script>window.location = "download.php";</script>

If you want this to work on a link, use this...

<a href='javascript:window.location = "download.php"'>
    Download it!
</a>

Solution 8 - Javascript

You can use download.js (https://github.com/rndme/download and http://danml.com/download.html). If the file is in an external URL, you must make an Ajax request, but if it is not, then you can use the function:

download(Path, name, mime)

Read their documentation for more details in the GitHub.

Solution 9 - Javascript

The solution that worked best for me was the one written up by Nick on his blog

The basic idea of his solution is to use the Apache servers header mod and edit the .htaccess to include a FileMatch directive that the forces all *.pdf files to act as a stream instead of an attachment. While this doesn't actually involve editing HTML (as per the original question) it doesn't require any programming per se.

The first reason I preferred Nick's approach is because it allowed me to set it on a per folder basis so PDF's in one folder could still be opened in the browser while allowing others (the ones we would like users to edit and then re-upload) to be forced as downloads.

I would also like to add that there is an option with PDF's to post/submit fillable forms via an API to your servers, but that takes awhile to implement.

The second reason was because time is a consideration. Writing a PHP file handler to force the content disposition in the header() will also take less time than an API, but still longer than Nick's approach.

If you know how to turn on an Apache mod and edit the .htaccss you can get this in about 10 minutes. It requires Linux hosting (not Windows). This may not be appropriate approach for all uses as it requires high level server access to configure. As such, if you have said access it's probably because you already know how to do those two things. If not, check Nick's blog for more instructions.

Solution 10 - Javascript

As the html5 way (my previous answer) is not available in all browsers, heres another slightly hack way.

This solution requires you are serving the intended file from same domain, OR has CORS permission.

  1. First download the content of the file via XMLHttpRequest(Ajax).
  2. Then make a data URI by base64 encoding the content of the file and set media-type to application/octet-stream. Result should look like

data:application/octet-stream;base64,SGVsbG8sIFdvcmxkIQ%3D%3D

Now set location.href = data. This will cause the browser to download the file. Unfortunately you can't set file name or extension this way. Fiddling with the media-type could yield something.

See details: https://developer.mozilla.org/en-US/docs/Web/HTTP/data_URIs

Solution 11 - Javascript

I needed to do this for files created with dynamic names in a particular folder and served by IIS.

This worked for me:

  • In IIS, go that folder and double click HTTP Response Headers.

  • Add a new header with the following info:

    Name: content-disposition Value: attachment

(from: http://forums.iis.net/t/1175103.aspx?add+CustomHeaders+only+for+certain+file+types+)

Solution 12 - Javascript

If you are using HTML5 (and i guess now a days everyone uses that), there is an attribute called download.

ex. <a href="somepathto.pdf" download="filename">

here filename is optional, but if provided, it will take this name for downloaded file.

Solution 13 - Javascript

I've had some issues with the suggested solution that creates an a DOM element, and sets the download attribute. It still displayed a popup warning in some browsers (perhaps they got a little stricter by 2021).

Adding the pdf mime type to the href attribute solved the browser popup warning, but it messed up the file (the downloaded file got damaged and couldn't be opened).

In 2021 you can download a PDF file without browser warnings, without PHP or Apache settings, using an XMLHttpRequest as suggested by Edhowler. His code example uses an npm library though. Here's how to do it using js only:

/**
 * Download a file without browser popup warning
 * @param {string} url The url of the file to download
 * @param {string} filename Set a new filename for the downloaded file (optional)
 */
const downloadFile = (url, filename = '') => {
  if (filename.length === 0) filename = url.split('/').pop();
  const req = new XMLHttpRequest();
  req.open('GET', url, true);
  req.responseType = 'blob';
  req.onload = function () {
    const blob = new Blob([req.response], {
      type: 'application/pdf',
    });

    const isIE = false || !!document.documentMode;
    if (isIE) {
      window.navigator.msSaveBlob(blob, filename);
    } else {
      const windowUrl = window.URL || window.webkitURL;
      const href = windowUrl.createObjectURL(blob);
      const a = document.createElement('a');
      a.setAttribute('download', filename);
      a.setAttribute('href', href);
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
    }
  };
  req.send();
};

downloadFile('https://domain.tld/file.pdf');

Use a transpiler like Babel if you need support for non ES6+ browsers.

Solution 14 - Javascript

The behaviour should depend on how the browser is set up to handle various MIME types. In this case the MIME type is application/pdf. If you want to force the browser to download the file you can try forcing a different MIME type on the PDF files. I recommend against this as it should be the users choice what will happen when they open a PDF file.

Solution 15 - Javascript

you can add the following code

<a href='http://v2.immo-facile.com/catalog/admin-v2/product_info.pdf' class='btnPdf' title='pdf'  target='_blank' type='application/pdf' >Télécharger la fiche du bien</a>

Solution 16 - Javascript

@Aljohn Yamaro

function forceDownload(pdf_url, pdf_name) {
    var x = new XMLHttpRequest();
    x.open("GET", pdf_url, true);
    x.responseType = 'blob';
    x.onload = function(e){
        saveAs(x.response, pdf_name, 'application/pdf');
    };
    x.send();
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Question404ErrorView Question on Stackoverflow
Solution 1 - JavascriptSarimView Answer on Stackoverflow
Solution 2 - JavascriptYiğit YenerView Answer on Stackoverflow
Solution 3 - JavascriptDA.View Answer on Stackoverflow
Solution 4 - JavascriptbeardhatcodeView Answer on Stackoverflow
Solution 5 - JavascriptmihsatheView Answer on Stackoverflow
Solution 6 - JavascriptPrasad JoshiView Answer on Stackoverflow
Solution 7 - JavascripthlozancicView Answer on Stackoverflow
Solution 8 - JavascriptVishnu S.View Answer on Stackoverflow
Solution 9 - JavascriptStrixyView Answer on Stackoverflow
Solution 10 - JavascriptSarimView Answer on Stackoverflow
Solution 11 - JavascriptEricLView Answer on Stackoverflow
Solution 12 - JavascriptAkshayView Answer on Stackoverflow
Solution 13 - JavascriptJKLView Answer on Stackoverflow
Solution 14 - JavascriptAleksi YrttiahoView Answer on Stackoverflow
Solution 15 - JavascriptNejmeddine JammeliView Answer on Stackoverflow
Solution 16 - JavascriptEdhowlerView Answer on Stackoverflow