如何使用JS自动下载PDF?

32

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

  1. 用户点击按钮
  2. JavaScript代码运行并自动下载PDF文件
  3. 使用JavaScript自动打开文件
  4. 用户填写并按提交
  5. 提交后,servlet代码运行并将数据保存在数据库中

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


document.location = 'url of pdf' - Jaromanda X
请更具体地说明。您是只需要像@JaromandaX上面展示的方法,还是需要更具体的说明? - Stephen Reindl
6个回答

82

使用download属性

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

太好了,它正常工作了。非常感谢。我们可以指定文件下载的路径吗?Chrome不会询问路径,而是使用JavaScript或HTML编程方式获取路径。 - Ehsaan Israr
@EhsaanIsrar 我们无法修改。浏览器通常使用用户设置来处理下载的文件。 - minj
1
非常感谢。你能告诉我如何在xhtml中自动下载吗?我正在使用基于Java的Liferay Portlet框架工作,其中视图是使用xhtml和PrimeFaces设计的。在这种情况下,有没有自动下载的方法? - Ehsaan Israr
2
2020年6月,最新版本的Chrome和Ubuntu 18.04上无法工作,请问是否需要进行任何更改?下载的文件显示“失败”、“无文件”错误,无法打开文件。除了createElement('a')之外,如何为任何div元素指定元素ID? - GD- Ganesh Deshmukh
2
这个不起作用。这会在最新的Chrome 2021年11月打开PDF文件。 - mending3
显示剩余5条评论

11

同时也可以在新窗口打开pdf链接,然后由浏览器处理其余部分:

window.open(pdfUrl, '_blank');

或者:

window.open(pdfUrl);

3
这个程序打开PDF文件时,有没有直接下载的方法? - Sunil Garg
这也可以工作,尽管新窗口会立即打开和关闭,这会导致用户体验不佳。 - Anastasis

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

如何使用?
download_file(fileURL, fileName); //call function

0
请尝试这个。

(function ($) {
    $(document).ready(function(){
       function validateEmail(email) {
            const re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
            return re.test(email);
           }
       
       if($('.submitclass').length){
            $('.submitclass').click(function(){
                $email_id = $('.custom-email-field').val();
                if (validateEmail($email_id)) {
                  var url= $(this).attr('pdf_url');
                  var link = document.createElement('a');
                  link.href = url;
                  link.download = url.split("/").pop();
                  link.dispatchEvent(new MouseEvent('click'));
                }
            });
       }
    });
}(jQuery));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post">
        <div class="form-item form-type-textfield form-item-email-id form-group">
            <input placeholder="please enter email address" class="custom-email-field form-control" type="text" id="edit-email-id" name="email_id" value="" size="60" maxlength="128" required />
        </div>
        <button type="submit" class="submitclass btn btn-danger" pdf_url="https://file-examples-com.github.io/uploads/2017/10/file-sample_150kB.pdf">Submit</button>
</form>

或者在 HTML5 中使用 download 属性 来标记标签


0
// Define the URL of the PDF file
var pdfUrl = "http://example.com/path/to/your/pdf.pdf";

// Function to trigger the download
function downloadPdf() {
  fetch(pdfUrl)
    .then(response => response.blob())
    .then(blob => {
      // Create a blob URL for the PDF data
      var url = window.URL.createObjectURL(blob);

      // Create a link element to trigger the download
      var a = document.createElement("a");
      a.href = url;
      a.download = "downloaded.pdf"; // Set the desired file name
      document.body.appendChild(a);

      // Trigger a click event on the link element to initiate the download
      a.click();

      // Clean up by revoking the blob URL and removing the link element
      window.URL.revokeObjectURL(url);
      document.body.removeChild(a);
    })
    .catch(error => {
      console.error("Failed to download the PDF file: ", error);
    });
}

// Call the downloadPdf() function when needed, e.g., in response to a button click
document.getElementById("downloadButton").addEventListener("click", downloadPdf);
  1. http://example.com/path/to/your/pdf.pdf替换为您要下载的PDF文件的实际URL。
  2. fetch()函数用于向PDF文件URL发出GET请求。
  3. 一旦收到响应,将PDF内容转换为blob,并创建一个blob URL。
  4. 动态创建一个锚元素(),并将其href属性设置为blob URL。您可以使用download属性指定所需的文件名。
  5. 将锚元素添加到文档的主体中。
  6. 通过编程方式在锚元素上触发点击事件以启动下载。
  7. 最后,撤销blob URL,并从文档中删除锚元素以进行清理。

您可以在按钮点击或任何其他用户操作中调用downloadPdf()函数以启动下载。


-3
  1. 对于第二点,将PDF文件的完整路径存储到某个Java变量中。例如:http://www.domain.com/files/filename.pdf

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

因此,您可以编写类似以下的JavaScript代码来模拟下载对话框:

<script language="javascript">
    window.location.href = '<?php echo $filepath; ?>';
</script

以上代码通过其URL“http://www.domain.com/files/filename.pdf”将浏览器发送到PDF文件。因此,最终,浏览器将显示下载对话框,询问您要在计算机上保存此文件的位置。

window.location.href 告诉的是文件的 URL,而不是下载文件。 - Ehsaan Israr
抱歉,我本意是说下面这样:应该像下面那样使用完全合格的 PDF 文件 URL:<script type="text/javascript"> window.location.href = 'http://www.domain.com/files/filename.pdf&#39; </script> - Alpesh Panchal
完整路径意味着如果您在浏览器地址栏中输入PDF的直接URL,您可以访问它。因此,完整的URL必须存在于PHP的$filepath变量中。 - Alpesh Panchal
非常感谢,但我不是用PHP实现。我必须使用Java,JSF和PrimeFaces。你能帮我吗? - Ehsaan Israr
抱歉,我不熟悉Java、JSF和PrimeFaces,但只需创建“filepath”变量即可。其余部分将自动处理。 - Alpesh Panchal
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接