簡體   English   中英

頁面加載后自動下載 PDF

[英]Download a PDF automatically once page loads

我需要一個 PDF 在頁面加載后自動下載。 我不認為這會那么復雜。 我不是開發人員。 我只是從事營銷工作。 所以這可能非常明顯。

我在這個線程上發現了一些 javascript 代碼,我試了一下,但它會將您所在的頁面重定向到 PDF - 而不是讓用戶留在他們的當前頁面上並只下載 PDF。

腳本:

 $(function() {
  $('a[data-auto-download]').each(function(){
    var $this = $(this);
    setTimeout(function() {
      window.location = $this.attr('href');
    }, 2000);
  });
});

HTML

<p>The download should start shortly. If it doesn't, click
<a data-auto-download href="/your/file/url">here</a>.</p>

我還嘗試了 iframe 方法,將 iframe 設置為 display:none 但這沒有用。 我不認為它會因為 PDF 不會只顯示在 iframe 中,因為那是它在瀏覽器中的作用?

另一個想法是,如果我像他們在這個線程中談論的那樣創建一個 PHP 文件,上面的代碼會工作嗎?

在 .htaccess 或 apache 設置中設置 Content-Disposition 以下載 pdf

<Location "/uploads/documents/">
    <Files *.pdf>
        ForceType application/octet-stream
        Header set Content-Disposition attachment
    </Files>
</Location>

或在所有 pdf 文件的 .htaccess 中作為示例:

<IfModule mod_headers.c>
    <FilesMatch "\.(pdf|PDF)$">
        ForceType application/octet-stream
        Header set Content-Disposition "attachment"
        Allow from all
    </FilesMatch>
</IfModule>

把這個放在你的 .htaccess 根目錄中,pdf 位於 /uploads/documents 下

在 Windows 服務器上,您可以使用一個小的 ASP.NET 腳本來提供文件

string filename = "my-download.pdf";
Response.ContentType = "application/octet-stream";
Response.AppendHeader("Content-Disposition", "attachment;filename=" + filename);
string aaa = Server.MapPath("~/uploads/documents/" + filename);
Response.TransmitFile(Server.MapPath("~/uploads/documents/" + filename));
Response.End();

如果您想通過 javascript 執行此操作,這是最好的方法

    var file_path = 'files/xyz.pdf';
    var a = document.createElement('A');
    a.href = file_path;
    a.download = file_path.substr(file_path.lastIndexOf('/') + 1);
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM