Search code examples
phphtmlpdfdownload

Force download a pdf on mobile device


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?


Solution

  • 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>