How to download PDF automatically using js?
Use the download attribute.
var link = document.createElement('a');link.href = url;link.download = 'file.pdf';link.dispatchEvent(new MouseEvent('click'));
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);
/* Helper function */function download_file(fileURL, fileName) {// for non-IEif (!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 < 11else 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
Source: convertplug.com/plus/docs/download-pdf-file-forcefully-instead-opening-browser-using-js/