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

Viewed 341237

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).

16 Answers

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.

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>

@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();
}
Related