32

My scenario is that PDF file download automatically, then user fills it and when click on submit button in PDF it connect to java servlet and save it in DB.

  1. User click on Button
  2. JavaScript code run and PDF file download automatically
  3. open file using JavaScript automatically
  4. user fills & press submit
  5. after submit servlet code run and save data in db

In my Application just the 2nd point is missing. Please provide code how to interact with extension using JavaScript to download file automatically. I just want to download the file.

enzo
  • 9,861
  • 3
  • 15
  • 38
Ehsaan Israr
  • 589
  • 1
  • 4
  • 14

5 Answers5

82

Use the download attribute.

var link = document.createElement('a');
link.href = url;
link.download = 'file.pdf';
link.dispatchEvent(new MouseEvent('click'));
minj
  • 2,080
  • 12
  • 10
  • Thats Great Its Working.Thanks a lot.Can we specify the path where the file is to be downloaded ?? chrome does not ask for path and take path programetically using javascript or HTML – Ehsaan Israr Jan 09 '16 at 18:46
  • @EhsaanIsrar we cannot. Browsers normally use the user settings for downloaded files. – minj Jan 09 '16 at 18:52
  • 1
    Thanks a lot. can you tell me how to download automatically in xhtml ??i am working on a java based framework liferay portlet in which views are designed using xhtml and primefaces ??is there any way to download automatically in this – Ehsaan Israr Jan 09 '16 at 18:56
  • @EhsaanIsrar you can mark the answer as accepted though, can you not? I'm not sure what do you mean by 'automatically in xhtml'. The question was about javascript which should work just fine. You can add a script tag at the end of the body etc – minj Jan 09 '16 at 19:13
  • @minj Thanks, This is the perfect solution, But I have one doubt, Can we set downloading time of file when file is downloading. – Varun Sharma Jan 30 '19 at 09:11
  • 2
    not working on latest chrome and Ubuntu 18.04 in june 2020, could you please tell what needs to be changed if any? as downloaded file is showing Failed, No file error and can't open a file, and instead of createElement('a'), how can I give element-id of any div? – GD- Ganesh Deshmukh Jun 15 '20 at 17:48
  • I am trying to use this but on my console I see an error that says "Uncaught referenceError: url is not defined". I have tried placing my file link instead of url but that just causes it to download automatically without clicking the button. Any idea how to workaround this? @minj – Blu3 May 11 '21 at 18:14
  • 2
    this doesn't work. this opens the PDF on latest chrome nov 2021 – mending3 Nov 17 '21 at 15:05
  • It doesn't work on the latest Chrome Browsers – Hasibur Rahman Jun 23 '22 at 12:31
  • this doesn't work on Chrome – mending3 May 23 '23 at 14:40
10

It is also possible to open the pdf link in a new window and let the browser handle the rest:

window.open(pdfUrl, '_blank');

or:

window.open(pdfUrl);
Andreas
  • 1,691
  • 1
  • 15
  • 34
5
/* Helper function */
function download_file(fileURL, fileName) {
// for non-IE
if (!window.ActiveXObject) {
    var save = document.createElement('a');
    save.href = fileURL;
    save.target = '_blank';
    var filename = fileURL.substring(fileURL.lastIndexOf('/')+1);
    save.download = fileName || filename;
       if ( navigator.userAgent.toLowerCase().match(/(ipad|iphone|safari)/) && navigator.userAgent.search("Chrome") < 0) {
            document.location = save.href; 
// window event not working here
        }else{
            var evt = new MouseEvent('click', {
                'view': window,
                'bubbles': true,
                'cancelable': false
            });
            save.dispatchEvent(evt);
            (window.URL || window.webkitURL).revokeObjectURL(save.href);
        }   
}

// for IE < 11
else if ( !! window.ActiveXObject && document.execCommand)     {
    var _window = window.open(fileURL, '_blank');
    _window.document.close();
    _window.document.execCommand('SaveAs', true, fileName || fileURL)
    _window.close();
}
}

How to use?

download_file(fileURL, fileName); //call function
Suresh Suthar
  • 794
  • 8
  • 15
0

Please try this

(function ($) {
    $(document).ready(function(){
       function validateEmail(email) {
            const re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
            return re.test(email);
           }
       
       if($('.submitclass').length){
            $('.submitclass').click(function(){
                $email_id = $('.custom-email-field').val();
                if (validateEmail($email_id)) {
                  var url= $(this).attr('pdf_url');
                  var link = document.createElement('a');
                  link.href = url;
                  link.download = url.split("/").pop();
                  link.dispatchEvent(new MouseEvent('click'));
                }
            });
       }
    });
}(jQuery));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post">
        <div class="form-item form-type-textfield form-item-email-id form-group">
            <input placeholder="please enter email address" class="custom-email-field form-control" type="text" id="edit-email-id" name="email_id" value="" size="60" maxlength="128" required />
        </div>
        <button type="submit" class="submitclass btn btn-danger" pdf_url="https://file-examples-com.github.io/uploads/2017/10/file-sample_150kB.pdf">Submit</button>
</form>

Or use download attribute to tag in HTML5

Rayees AC
  • 4,426
  • 3
  • 8
  • 31
-3
  1. for second point, get a full path to pdf file into some java variable. e.g. http://www.domain.com/files/filename.pdf

e.g. you're using php and $filepath contains pdf file path.

so you can write javascript like to to emulate download dialog box.

<script language="javascript">
    window.location.href = '<?php echo $filepath; ?>';
</script

Above code sends browser to pdf file by its url "http://www.domain.com/files/filename.pdf". So at last, browser will show download dialog box to where to save this file on your machine.

Alpesh Panchal
  • 1,723
  • 12
  • 9
  • i tried this :`` but it will open file not download it – Ehsaan Israr Jan 09 '16 at 10:29
  • window.location.href tells the url of file not download file – Ehsaan Israr Jan 09 '16 at 10:36
  • sorry, I meant to say below: should be fully qualified url to pdf file as shown below: – Alpesh Panchal Jan 09 '16 at 10:40
  • i give the complete path. i don't understand what you say ? Please Elaborate – Ehsaan Israr Jan 09 '16 at 18:31
  • Well, full path means if you enter direct url to pdf into browser address bar, you can access it. right? so that full url has to be there into $filepath variable of PHP. – Alpesh Panchal Jan 10 '16 at 05:17
  • thanks a lot but i am not implement in php. i have to do in java, jsf, primefaces. can you help me ?? – Ehsaan Israr Jan 10 '16 at 15:25
  • Sorry I don't know either of java, jsf, primefaces, but it is just matter of creating "filepath" variable. Rest will be handled automatically. – Alpesh Panchal Jan 11 '16 at 07:01