如何使用js自动下载PDF?

Ehs*_*rar 9 javascript pdf jquery plugins google-chrome-extension

我的场景是自动下载PDF文件,然后用户填写它,当点击PDF中的提交按钮时,它连接到java servlet并将其保存在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
Run Code Online (Sandbox Code Playgroud)

在我的应用程序中,仅缺少第二点.请提供代码如何使用JavaScript自动下载文件与扩展交互.我只想下载文件.

min*_*inj 37

使用下载属性.

var link = document.createElement('a');
link.href = url;
link.download = 'file.pdf';
link.dispatchEvent(new MouseEvent('click'));
Run Code Online (Sandbox Code Playgroud)

  • 这是行不通的。这将在最新的 chrome 2021 年 11 月上打开 PDF (3认同)
  • 无法在 2020 年 6 月最新的 chrome 和 Ubuntu 18.04 上运行,您能否告诉我们需要更改哪些内容(如果有)?由于下载的文件显示失败、无文件错误并且无法打开文件,而不是 createElement('a'),我如何给出任何 div 的元素 id? (2认同)

And*_*eas 5

也可以在新窗口中打开 pdf 链接,让浏览器处理其余部分:

window.open(pdfUrl, '_blank');
Run Code Online (Sandbox Code Playgroud)

或者:

window.open(pdfUrl);
Run Code Online (Sandbox Code Playgroud)

  • 这是在新窗口中打开pdf文件,有什么办法可以直接下载吗? (3认同)

Sur*_*har 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();
}
}
Run Code Online (Sandbox Code Playgroud)

如何使用?

download_file(fileURL, fileName); //call function
Run Code Online (Sandbox Code Playgroud)