Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

458
Vistas
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.

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

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,
        }
      )
    });
})
about 4 years ago · Juan Pablo Isaza Denunciar

0

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)
about 4 years ago · Juan Pablo Isaza Denunciar

0

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>
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda