I need to print images in various sizes, and I can't understand why the result of my variable imgHeight sometimes has different values.
This is the method I'm using to process the pdf
async addImageToPdf(elementId: string) {
const thumbnailsHtml = document.getElementById(elementId) as HTMLElement;
await this.sleep(500);
const canvas = await html2canvas(thumbnailsHtml, { useCORS: true });
const imgData = canvas.toDataURL("image/jpeg", 1.0);
await this.sleep(500);
const imgProps = this.pdf.getImageProperties(imgData);
const pdfWidth = 210 /* this.pdf.internal.pageSize.getWidth() */;
const pageHeight = this.pdf.internal.pageSize.getHeight() + 40;
const imgHeight = (imgProps.height * pdfWidth) / imgProps.width;
console.log(imgProps);
console.log(imgHeight);
var heightLeft = imgHeight;
var position = 0;
this.pdf.addImage(
imgData,
"JPEG",
15, // Position of image from left and right
10, // Position of image from top and bottom
pdfWidth,
imgHeight
);
heightLeft -= pageHeight;
while (heightLeft >= 0) {
position = heightLeft - imgHeight;
this.pdf.addPage();
this.pdf.addImage(
imgData,
"JPEG",
5,
position + 52,
pdfWidth,
imgHeight
);
heightLeft -= pageHeight;
}
},
This is what my pdf should look like
And this is what happens SOMETIMES
The second plan image should be below the first one and not in the left like it shows. These are two different prints with the same code.