How to download PDF automatically using js?

∥☆過路亽.° 提交于 2019-12-18 01:04:29

问题


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.


回答1:


Use the download attribute.

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



回答2:


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);



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



来源:https://stackoverflow.com/questions/34691525/how-to-download-pdf-automatically-using-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!