Untitled

 avatar
user_8823367
plain_text
a year ago
1.8 kB
0
Indexable
Never
let policy = null;

if(window.trustedTypes && trustedTypes.createPolicy) { // Check if TrustedTypes are available
    policy = trustedTypes.createPolicy('myPolicy', { 
        createScriptURL: (stringURL) => stringURL // Simplest policy
    });
}

let jspdf = document.createElement("script");
 
jspdf.onload = function () {
 
    let pdf = new jsPDF('p', 'mm', 'a4'); // Create A4 portrait pages
    let pageHeight = pdf.internal.pageSize.getHeight();
    let pageWidth = pdf.internal.pageSize.getWidth();
    
    let elements = document.getElementsByTagName("img");
    for (let i in elements) {
        let img = elements[i];
        console.log("add img ", img);
        if (!/^blob:/.test(img.src)) {
            console.log("invalid src");
            continue;
        }
        let can = document.createElement('canvas');
        let con = can.getContext("2d");
        can.width = img.width;
        can.height = img.height;
        con.drawImage(img, 0, 0, can.width, can.height);
        let imgData = can.toDataURL("image/jpeg", 1.0);
        
        // Adjust the image dimensions to fit the page
        let imgProps = pdf.getImageProperties(imgData);
        let pdfWidth = pageWidth;
        let pdfHeight = (imgProps.height * pdfWidth) / imgProps.width;
        
        pdf.addImage(imgData, 'JPEG', 0, 0, pdfWidth, pdfHeight);
        pdf.addPage();
    }

    pdf.deletePage(pdf.internal.getNumberOfPages()); // Remove the last empty page
 
    pdf.save("download.pdf");
};
 
jspdf.src = policy ? policy.createScriptURL('https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.debug.js') : 'https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.debug.js';
document.body.appendChild(jspdf);