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

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

This question is related to javascript html

The answer is


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


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


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.


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.


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

Content-Disposition: attachment; filename=fname.ext

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


With html5, it is possible now. Set a "download" attr in element.

<a href="http://link/to/file" download="FileName">Download it!</a>

Source : http://updates.html5rocks.com/2011/08/Downloading-resources-in-HTML5-a-download


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.


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.


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


you can add the following code

_x000D_
_x000D_
<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>
_x000D_
_x000D_
_x000D_


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>

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.