简体   繁体   中英

How to download PDF automatically on click instead of opening it in new tab using js?

I have an input URL with which I want to download pdf file directly without viewing it in a new tab or on the same tab, I have tried following things till now but nothing is helping. Frist tried with this

http.success(function (data) {
  var link = document.createElement('a');
  link.href = data.results[0].value.url;
  link.download = data.results[0].value.url.substr(data.results[0].value.url.lastIndexOf('/') + 1);
  link.click();
  document.body.appendChild(link);
  setTimeout(function () {
  document.body.removeChild(link);
     }, 100);
}.bind(this));

This script is not downloading the file. It opens the file in the same tab. Have tried all the answers in these previously answered questions. But nothing worked for me. How can I download a pdf from a url using javascript? How to download PDF automatically using js? Download pdf without opening in browser

Then I tried with this Blob . Added the blob to my script and then tried again.

http.success(function (data) {
  var blob=new Blob([data.results[0].value.url],{ type: "application/pdf" });
  var link = document.createElement('a');
  link.href = window.URL.createObjectURL(blob);
  link.download = data.results[0].value.url.substr(data.results[0].value.url.lastIndexOf('/') + 1);
  link.click();
  document.body.appendChild(link);
  setTimeout(function () {
  document.body.removeChild(link);
     }, 100);
}.bind(this));

But this time it downloads the file. But can't able to open it. The downloaded file is corrupted. Have tried the answers in these questions. But nothing worked for me. PDF is corrupted after reconstructing it using URL.createObjectURL Problem downloading a PDF blob in JavaScript Blob from buffer returns corrupted pdf

please let me know if there are any other ways to download the pdf file directly. Thanks in advance.

What is stored in data.results[0].value.url?

Is it just a link to the PDF? If that's the case you will need to fetch the pdf document first.

Try this

http.success(function (data) {
  fetch(data.results[0].value.url)
    .then((response) => response.arrayBuffer())
    .then((pdfFile) => {
      const blob = new Blob([pdfFile], { type: "application/pdf" });

      const anchor = document.createElement("a");

      anchor.href = window.URL.createObjectURL(blob);
      anchor.download = "SOME FILENAME.PDF";
      // some browser needs the anchor to be in the doc
      document.body.append(anchor);
      anchor.click();
      anchor.remove();
      // in case the Blob uses a lot of memory
      window.addEventListener(
        "focus",
        () => {
          URL.revokeObjectURL(anchor.href);
        },
        {
          once: true,
        }
      )
    });
})

First, I would recommend trying the simplest example.

const pdfLink = data.results[0].value.url

const download = (url) => {
    const link = document.createElement('a');

    link.setAttribute('download', 'fileName.pdf');
    link.setAttribute('href', url);
    link.click();
}

downloadBlob = (blob) => download(URL.createObjectURL(blob))

fetch(pdfLink)
  .then(response => response.blob())
  .then(downloadBlob)

I share you a piece of code using MUI + JS

<IconButton variant="contained"
                      sx={{
                        fontSize: '1rem',
                        fontWeight: 'normal',
                        color:'silver',
                      }}
                      component='label'
                      size={'small'}
                      onClick={() => {
                        const url = 'https:.....'
                        fetch(url)
                          .then((res) => { return res.blob(); })
                          .then((data) => {
                            const a = document.createElement("a")
                            a.href = window.URL.createObjectURL(data)
                            a.download = formValues[id]
                            a.click()
                          });
                      }}>
    <VisibilityIcon />
</IconButton>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM