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);
})();
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.