import html2canvas from 'html2canvas'; import jsPDF from 'jspdf'; document.addEventListener('DOMContentLoaded', function () { const printButton = document.querySelector('[ns-printonpage-element="button"]'); const printTargets = document.querySelectorAll('[ns-printonpage-element="target"]'); const documentTitleElement = document.querySelector('[ns-printonpage-title]'); const documentInstitution = document.querySelector( '[ns-printonpage-institution]' ) as HTMLInputElement; let documentTitle: string; if (documentTitleElement) { documentTitle = documentTitleElement.getAttribute('ns-printonpage-title') || ''; } else { documentTitle = document.title; } if (documentInstitution) { const institution = documentInstitution.value || ''; documentTitle = `${documentTitle} - ${institution}`; } async function generatePdf() { const pdf = new jsPDF('p', 'pt', 'a4'); if (printButton) printButton.textContent = 'Téléchargement en cours...'; for (const target of printTargets) { const wrapper = document.createElement('div'); wrapper.style.padding = '96px'; wrapper.style.boxSizing = 'border-box'; wrapper.style.maxWidth = '595.28px'; // Adjust width for responsiveness const titleElement = document.createElement('h1'); titleElement.textContent = documentTitle; titleElement.style.fontSize = '24px'; titleElement.style.margin = '0 0 20px 0'; wrapper.appendChild(titleElement); const dateElement = document.createElement('p'); const currentDate = new Date(); const formattedDate = currentDate.toLocaleString(); dateElement.textContent = `Date: ${formattedDate}`; dateElement.style.paddingBottom = '48px'; wrapper.appendChild(dateElement); const clonedTarget = target.cloneNode(true); wrapper.appendChild(clonedTarget); document.body.appendChild(wrapper); const canvas = await html2canvas(wrapper, { useCORS: true, scale: 1 }); // Scale down for better quality-to-size ratio const imgData = canvas.toDataURL('image/jpeg', 0.8); // Use JPEG for better compression const imgWidth = 595.28; const pageHeight = 841.89; const imgHeight = (canvas.height * imgWidth) / canvas.width; let heightLeft = imgHeight; let position = 0; pdf.addImage(imgData, 'JPEG', 0, position, imgWidth, imgHeight, 'FAST'); // Use FAST for better performance heightLeft -= pageHeight; while (heightLeft >= 0) { position = heightLeft - imgHeight; pdf.addPage(); pdf.addImage(imgData, 'JPEG', 0, position, imgWidth, imgHeight, 'FAST'); heightLeft -= pageHeight; } document.body.removeChild(wrapper); } pdf.save(`${documentTitle}.pdf`); if (printButton) printButton.textContent = 'PDF téléchargé !'; } if (printButton) { printButton.addEventListener('click', () => { generatePdf(); }); } });