Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

348
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!