In my application I got a button that creates a pdf using html2canvas and jsPDF. I'd like the new downloaded pdf be opened in new tab. I cannot figure out how to open newly downloaded file.
Is this even possible to do?
This is my code.
print() {
const fileName = String(new Date().valueOf());
const element: HTMLElement = document.querySelector('.print-area');
const regionCanvas = element.getBoundingClientRect();
html2canvas(element, { scale: 3 }).then(async canvas => {
const pdf = new jsPDF('p', 'mm', 'a4');
pdf.addImage(canvas.toDataURL('image/png'), 'PNG', 3, 0, 205, (205 / regionCanvas.width) * regionCanvas.height);
await pdf.save(fileName, { returnPromise: true });
const a = document.createElement('a');
a.href = fileName;
// this points to non existing file
document.body.appendChild(a);
});
}
I found a way to download and open a file. You have to basically call two functions:
pdf.save(fileName);
window.open(pdf.output('bloburl', { filename: fileName }), '_blank');
So the code in the end looks like this:
print() {
const fileName = String(new Date().valueOf());
const element: HTMLElement = document.querySelector('.print-area');
const regionCanvas = element.getBoundingClientRect();
html2canvas(element, { scale: 3 }).then(async canvas => {
const pdf = new jsPDF('p', 'mm', 'a4');
pdf.addImage(canvas.toDataURL('image/png'), 'PNG', 3, 0, 205, (205 / regionCanvas.width) * regionCanvas.height);
await pdf.save(fileName, { returnPromise: true });
window.open(pdf.output('bloburl', { filename: fileName }), '_blank');
});
}