How to download a pdf file (blob) on mobile iOS Safari/Chrome in 2024


There are plenty of threads around the Internet on this topic but most of them seem to be 3-5+ years old. Or the answers touch upon MacOS Safari.
I’m explicitly asking for Safari on iPhone.

I have the following piece of code:

const downloadPdf = async () => {
  try {
    const pdfBinaryRes = await fetchPdfFile()

    if (!pdfBinaryRes.ok) {
      throw new Error(`HTTP error! Status: ${pdfBinaryRes.status}`)
    }

    const filename = pdfBinaryRes.headers... //do magic

    const pdfBlob = await pdfBinaryRes.blob()

    const blobUrl = window.URL.createObjectURL(pdfBlob)

    const link = document.createElement('a')
    link.href = blobUrl
    link.download = filename
    link.click()

    setTimeout(() => {
      window.URL.revokeObjectURL(blobUrl)
    }, 250)
  } catch (error) {
    console.error(error)
  }
}

content-type: application/pdf;charset=UTF-8

content-disposition: attachment; filename=my-pdf.pdf

iOS Safari/Chrome opens the blob URL in the same tab with URL blob:https://….
The pdf file is previewed but I’d like to be able to save it as .pdf file in the file system.

On the contrary browsers on Android save the file (and then open it, but I guess this is another story on its own)

  • a.download attribute was not supported in iOS Safari until v13, but now it should be
  • this bug seems to have been resolved already

Latest articles

spot_imgspot_img

Related articles

Leave a reply

Please enter your comment!
Please enter your name here

spot_imgspot_img