skip to Main Content

I want to force a pdf to be downloaded on mobile/tablet device to avoid open it in a new tab.

I tried with the download attribute:

<a href="file.pdf" download target="_blank">

It works on desktop but not on mobile.

I also tried with PHP header:

header('Content-Type: application/pdf');
header('Content-Transfer-Encoding: Binary');
header('Content-Disposition: attachment; filename="file.pdf"');
readfile('https://my-website.com/file.pdf');

But same, it works on desktop but not on mobile.

Any way to do this?

2

Answers


  1. Chosen as BEST ANSWER

    I did it in Javascript using blob:

    <a href="#" id="download">DOWNLOAD</a>
    
    <script>
    function startPdfDownload(name = 'file.pdf', type = 'application/octetstream') {
      // Online file link
      const url = "https://website.com/file.pdf";
    
      // Create XMLHTTP Request.
      var req = new XMLHttpRequest();
      req.open("GET", url, true);
      req.responseType = "blob";
      req.onload = function () {
        const blob = new Blob([req.response], { type: type });
    
        const { URL: { createObjectURL, revokeObjectURL }, setTimeout } = window
        link = createObjectURL(blob);
    
        // Create download anchor
        const a = document.createElement("a");
        a.setAttribute("download", name);
        a.setAttribute("href", link);
        document.body.appendChild(a);
        a.click();
    
        setTimeout(() => { revokeObjectURL(url) }, 100)
        document.body.removeChild(a);
      };
      req.send();
    }
    
    document.getElementById('download').onclick = function() {
       startPdfDownload('file.pdf');
    };
    </script>
    

  2. I think you’re doing it as best as you can. If the <a> tag tells the browser to download it as well as your Content-Type and Content-Disposition headers, then the browser just doesn’t want to download it.

    You could try to confuse the browser by sending a Content-Type value that the browser doesn’t know, then it might fall back to download as the default behavior, but I wouldn’t do that. It reminds me of the User-Agent header, which is nowadays useless exactly because people were misusing it to confuse other parties until it lost all relevance.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search