You are on page 1of 1

let jspdf = document.

createElement("script");

jspdf.onload = function () {
let pdf = new jsPDF();
let elements = document.getElementsByTagName("img");

for (let i = 0; i < elements.length; i++) {


let img = elements[i];
console.log("add img ", img);
if (!(img instanceof HTMLImageElement) || !/^blob:/.test(img.src)) {
console.log("invalid src");
continue;
}

// Create a canvas with natural dimensions of the image


let can = document.createElement('canvas');
can.width = img.naturalWidth;
can.height = img.naturalHeight;
let con = can.getContext("2d");

// Draw the image on the canvas


con.drawImage(img, 0, 0, img.naturalWidth, img.naturalHeight);

// Add the image to the PDF with natural dimensions


pdf.addImage(can.toDataURL("image/jpeg", 1.0), 'JPEG', 0, 0,
pdf.internal.pageSize.width, pdf.internal.pageSize.height);

// Add a new page for the next image


if (i < elements.length - 1) {
pdf.addPage();
}
}

pdf.save("download.pdf");
};

jspdf.src = 'https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.debug.js';
document.body.appendChild(jspdf);

You might also like