AHA Recommended Limit
${recommendation}g
Your Food Log
${foodLogHtml}
Final Result
${totalSugar.toFixed(1)}g
${totalSugar > recommendation ? 'You are over the daily recommended limit.' : 'You are within the daily recommended limit.'}
`;
await new Promise(resolve => setTimeout(resolve, 100));
// 2. Use html2canvas to capture the content
try {
const canvas = await html2canvas(pdfExportContent, {
scale: 2, // A scale of 2 provides good quality without a huge file size
useCORS: true,
logging: false
});
const imgData = canvas.toDataURL('image/png');
// **FIX**: Create a standard A4 PDF and scale the image to fit within its margins.
// This prevents content from being cut off at the page edges.
const pdf = new jsPDF({
orientation: "portrait",
unit: "pt", // Use points for standard PDF sizing
format: "a4"
});
const pageWidth = pdf.internal.pageSize.getWidth();
const pageHeight = pdf.internal.pageSize.getHeight();
const margin = 40; // 40pt margin on each side
const imageWidth = canvas.width;
const imageHeight = canvas.height;
const aspectRatio = imageWidth / imageHeight;
// Calculate the width and height of the image on the PDF to fit the page
let pdfImageWidth = pageWidth - (margin * 2);
let pdfImageHeight = pdfImageWidth / aspectRatio;
// If the scaled height is still too big for the page, you might need multi-page logic.
// For this tool, we assume it will fit on one page.
if (pdfImageHeight > pageHeight - (margin * 2)) {
pdfImageHeight = pageHeight - (margin * 2);
pdfImageWidth = pdfImageHeight * aspectRatio;
}
const x = (pageWidth - pdfImageWidth) / 2; // Center the image
pdf.addImage(imgData, 'PNG', x, margin, pdfImageWidth, pdfImageHeight);
pdf.save(`Sugar-Intake-Report-${new Date().toISOString().slice(0,10)}.pdf`);
} catch (error) {
console.error("Error generating PDF:", error);
alert("Sorry, there was an error creating the PDF. Please check your browser console for details and try again.");
} finally {
// 4. Clean up
pdfLoader.classList.add('hidden');
pdfDownloadBtn.disabled = false;
pdfExportContent.innerHTML = ''; // Clear the content after generation
}
}
// --- START THE APP ---
initialize();
});