0

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?

1
  • 1
    In the old days, setting the content type to application/octet-stream was a trick to force the download, I wouldn't be surprised if that still works these days, unless sniffing is getting smarter. That said, I also wouldn't be surprised if iOS very specifically ignored this and did whatever they wanted
    – Chris Haas
    Commented Jun 24 at 20:02

2 Answers 2

1

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.

1

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>

Not the answer you're looking for? Browse other questions tagged or ask your own question.