Javascript 如何使用js自动下载PDF?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34691525/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 16:45:01  来源:igfitidea点击:

How to download PDF automatically using js?

javascriptjquerypdfpluginsgoogle-chrome-extension

提问by Ehsaan Israr

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.

我的场景是自动下载 PDF 文件,然后用户填写它,当点击 PDF 中的提交按钮时,它连接到 java servlet 并将其保存在数据库中。

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.

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

回答by minj

Use the download attribute.

使用下载属性

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

回答by Andreas

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

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

window.open(pdfUrl, '_blank');

or:

或者:

window.open(pdfUrl);

回答by Alpesh Panchal

  1. for second point, get a full path to pdf file into some java variable. e.g. http://www.domain.com/files/filename.pdf
  1. 对于第二点,将 pdf 文件的完整路径放入某个 java 变量中。例如http://www.domain.com/files/filename.pdf

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

例如,您正在使用 php 并且 $filepath 包含 pdf 文件路径。

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

所以你可以写javascript来模拟下载对话框。

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

上面的代码通过它的网址“ http://www.domain.com/files/filename.pdf”将浏览器发送到pdf文件。所以最后,浏览器会显示下载对话框到你的机器上保存这个文件的位置。