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

351
Vistas
Async await not working on html2pdf command

I am using html2pdf to generate and save pdf. Then I am using fetch to get pdf data. Problem is that my await is not working on html2pdf() line. If I use settimeout on fetch then it's working correctly. Using await is giving me 404 error. Following is my code.

(async () => {
  var element = document.getElementById('canvas_div_pdf');
  var opt = {
    pagebreak: { before: '.beforeClass' },
    image: { type: 'jpeg', quality: 1 },
  };
  let pdfData;
  let timestamp = +new Date();

  await html2pdf()
    .set(opt)
    .from(element)
    .toPdf()
    .get('pdf')
    .then(function (pdf) {
      var totalPages = pdf.internal.getNumberOfPages();
      // page numbers
      for (i = 1; i <= totalPages; i++) {
        pdf.setPage(i);
        pdf.setFontSize(10);
        pdf.setTextColor(150);
        pdf.text(
          'Page ' + i + ' of ' + totalPages,
          pdf.internal.pageSize.getWidth() - 30,
          pdf.internal.pageSize.getHeight() - 10
        );
      }
    })
    .save(timestamp + '.pdf');

  await fetch(timestamp + '.pdf')
    .then((response) => response.text())
    .then((text) => {
      console.log(text);
      pdfData = text;
    });

  const rawResponse = await fetch('api/pdf', {
    method: 'POST',
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json',
    },
    body: pdfData,
  });
  const content = await rawResponse.json();
  console.log(content);
})();
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

I did not run this code but first idea You may try is to :

const pdf = await html2pdf().set(opt).from(element).toPdf().get('pdf');

var totalPages = pdf.internal.getNumberOfPages();
// page numbers
for (i = 1; i <= totalPages; i++) {
  pdf.setPage(i);
  pdf.setFontSize(10);
  pdf.setTextColor(150);
  pdf.text(
    'Page ' + i + ' of ' + totalPages,
    pdf.internal.pageSize.getWidth() - 30,
    pdf.internal.pageSize.getHeight() - 10
  );
}

pdf.save();

What I mean is that you use await and then together which will not work. What you should do is to have async used on promise and then operate on result.

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