${wrapSections(htmlContent)}
`;
// Render for on-screen view
outputContainer.innerHTML = `
${fullReportHtml}
`;
// Prepare content for PDF generation
pdfTemplate.innerHTML = fullReportHtml;
// Add event listener to the new download button
document.getElementById('download-pdf-btn').addEventListener('click', () => {
generatePdf(pdfTemplate, `Study-Guide-${topic.replace(/ /g, '_')}.pdf`);
});
}
async function generatePdf(element, fileName) {
const downloadBtn = document.getElementById('download-pdf-btn');
if (!downloadBtn) return;
const originalButtonText = downloadBtn.innerHTML;
downloadBtn.innerHTML = 'Downloading...';
downloadBtn.disabled = true;
// Temporarily make the hidden element visible for rendering, but off-screen
element.classList.remove('invisible', 'absolute', '-left-full');
element.style.position = 'absolute';
element.style.left = '-9999px';
element.style.display = 'block';
try {
const { jsPDF } = window.jspdf;
const canvas = await html2canvas(element, {
scale: 3, // Increased scale for higher quality and larger file size
backgroundColor: '#ffffff', // Explicitly set background
useCORS: true
});
const imgData = canvas.toDataURL('image/png');
const pdf = new jsPDF({
orientation: 'p',
unit: 'pt',
format: 'a4'
});
const pdfWidth = pdf.internal.pageSize.getWidth();
const pdfHeight = (canvas.height * pdfWidth) / canvas.width;
pdf.addImage(imgData, 'PNG', 0, 0, pdfWidth, pdfHeight);
pdf.save(fileName);
} catch(err) {
console.error("PDF generation error:", err);
showNotification("Sorry, there was an issue creating the PDF.", true);
} finally {
// Restore original styles to hide the element again
element.classList.add('invisible', 'absolute', '-left-full');
element.style.position = '';
element.style.left = '';
element.style.display = '';
downloadBtn.innerHTML = originalButtonText;
downloadBtn.disabled = false;
}
}
function setLoadingState(isLoading) {
if (isLoading) {
generateBtn.disabled = true;
generateBtn.innerHTML = `Generating...`;
} else {
generateBtn.disabled = false;
generateBtn.innerHTML = `Generate Study Guide`;
}
}
});
