I have a form button, when clicked it submits the form.
I'd like that at the same time, the browser starts downloading a PDF file. I wonder how can I do this? Please keep in mind that PDF are usually opened by the browser by default, but I'd like the browser to "Save As" the file and not open the file. Is this do-able using html only or do I need javascript?
I have a form button, when clicked it submits the form.
I'd like that at the same time, the browser starts downloading a PDF file. I wonder how can I do this? Please keep in mind that PDF are usually opened by the browser by default, but I'd like the browser to "Save As" the file and not open the file. Is this do-able using html only or do I need javascript?
Share Improve this question asked Jun 5, 2012 at 16:28 James GuJames Gu 1,3924 gold badges27 silver badges39 bronze badges4 Answers
Reset to default 2If you are using PHP in the server side try this. This is tested code which is running in one of my websites.
<?php
ob_start();
$file = 'YOUR-FILENAME-HERE.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();
}
?>
Browser will prompt to download without displaying it in the browser.
You can use this plugin to download the files using javascript.
Otherwise in javascript, you can write code for it.
$('a').click(function(e) {
e.preventDefault(); //stop the browser from following
window.location.href = 'downloads/file.pdf';
});
<a href="no-script.html">Download now!</a>
Or, you can use this .
In PHP :
<?php
header('Content-type: application/pdf');
header('Content-disposition: attachment; filename=filename.pdf');
readfile("file.pdf");
?>
In Javascript :
<body>
<script>
function downloadme(x){
winObj = window.open(x,'','left=10000,screenX=10000');
winObj.document.execCommand('SaveAs','null','download.pdf');
winObj.close();
}
</script>
<a href=javascript:downloadme('file.pdf');>Download this pdf</a>
</body>
In that case, you'd have to configure your webserver to force a PDF to Download. If you're using Apache, you might as well take a look at this article -> http://www.thingy-ma-jig.co.uk/ment/7264
Or, if you don't have to support all browsers, you could get away with just using the html5 download attribute -> http://updates.html5rocks./2011/08/Downloading-resources-in-HTML5-a-download
Option 1: You can let the url, which your form submits to, return the download.
Option 2: Use an ajax call to submit the data onclick, set the window.location to your download url.
Whether the pdf is opened in the browser or downloaded, is a client side setting which you cannot control.