问题
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:
- 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