`;
// Update the output div
storyOutputDiv.innerHTML = storyHTML;
// Show the download button
downloadBtn.style.display = 'inline-block';
}
// Event Listener for Generate Button
generateBtn.addEventListener('click', generateStory);
// Event Listener for Download Button
downloadBtn.addEventListener('click', function() {
console.log("Download button clicked. Generating PDF...");
// Ensure the story content is current (optional, but safe)
// generateStory(); // Usually not needed if button only appears after generation
const elementToPrint = storyOutputDiv; // The div containing the story
// Scroll window slightly above the element to help ensure capture starts correctly
window.scrollTo(0, elementToPrint.offsetTop - 30); // Adjusted offset
// Get character name for filename
const charNameForFile = (charNameInput.value.trim() || "Hero").replace(/[^a-z0-9]/gi, '_'); // Sanitize
const filename = `Cartoon_Adventure_${charNameForFile}.pdf`;
const opt = {
margin: [0.6, 0.6, 0.6, 0.6], // Slightly larger margin for storybook feel
filename: filename,
image: { type: 'jpeg', quality: 0.97 }, // High quality JPEG
html2canvas: {
scale: 2,
logging: false,
useCORS: true,
y: 0 // Start capture from the top of the element's calculated position
},
jsPDF: { unit: 'in', format: 'letter', orientation: 'portrait' },
pagebreak: { mode: ['avoid-all', 'css', 'legacy'] }
};
// Add delay before processing PDF
setTimeout(() => {
console.log("Attempting PDF generation after scroll and delay...");
html2pdf().from(elementToPrint).set(opt).save().then(function() {
console.log("PDF generation complete.");
}).catch(function(error) {
console.error("Error generating PDF:", error);
alert("An error occurred while generating the PDF. Please check the console for details.");
});
}, 300); // 300ms delay
});
});
