import { jsPDF } from 'jspdf'; import html2canvas from 'html2canvas'; export const exportAsPdf = async (elementId: string, fileName: string, action: 'preview' | 'download'): Promise => { const element = document.getElementById(elementId); if (!element) { console.error(`Element with id ${elementId} not found.`); return; } try { // We temporarily make the element visible to html2canvas if it's hidden by CSS // by cloning it or just capturing it directly (html2canvas can capture off-screen if it's positioned absolute) const canvas = await html2canvas(element, { scale: 2, // Higher resolution useCORS: true, logging: false, backgroundColor: '#ffffff' // Ensure white background }); const imgData = canvas.toDataURL('image/jpeg', 0.95); // A4 dimensions in mm: 210 x 297 const pdf = new jsPDF({ orientation: 'portrait', unit: 'mm', format: 'a4', }); const pdfWidth = pdf.internal.pageSize.getWidth(); const pdfHeight = (canvas.height * pdfWidth) / canvas.width; pdf.addImage(imgData, 'JPEG', 0, 0, pdfWidth, pdfHeight); if (action === 'download') { pdf.save(`${fileName}.pdf`); } else { const pdfBlob = pdf.output('blob'); const pdfUrl = URL.createObjectURL(pdfBlob); window.open(pdfUrl, '_blank'); URL.revokeObjectURL(pdfUrl); } } catch (error) { console.error('Error generating PDF with html2canvas:', error); } };