Poem Structure Template
${summary}
- ${rulesHtml}
Untitled Poem
`;
renderHTML += `(${template.name})
`;
let lineCounter = 0;
template.stanzas.forEach(stanza => {
renderHTML += ``;
for (let i = 0; i < stanza.lines; i++) {
const lineText = poemLines[lineCounter]?.innerText.trim() || " ";
renderHTML += `
`;
});
elements.pdfRenderArea.innerHTML = renderHTML;
elements.pdfRenderArea.style.display = 'block';
// 2. Use html2canvas to capture the constructed HTML
try {
const canvas = await html2canvas(elements.pdfRenderArea, {
scale: 2, // Improve resolution
backgroundColor: null,
});
const imgData = canvas.toDataURL('image/png');
// 3. Create PDF and add the image
const pdf = new jsPDF({
orientation: 'p',
unit: 'px',
format: 'a4'
});
const pdfWidth = pdf.internal.pageSize.getWidth();
const pdfHeight = pdf.internal.pageSize.getHeight();
const canvasWidth = canvas.width;
const canvasHeight = canvas.height;
const ratio = canvasWidth / canvasHeight;
let imgWidth = pdfWidth - 40; // with margin
let imgHeight = imgWidth / ratio;
if (imgHeight > pdfHeight - 40) {
imgHeight = pdfHeight - 40;
imgWidth = imgHeight * ratio;
}
const x = (pdfWidth - imgWidth) / 2;
const y = 20;
pdf.addImage(imgData, 'PNG', x, y, imgWidth, imgHeight);
pdf.save(`${template.name.replace(/\s/g, '_')}_poem.pdf`);
} catch (error) {
console.error("Failed to generate PDF:", error);
alert("Sorry, there was an error creating the PDF.");
} finally {
// 4. Cleanup
elements.pdfRenderArea.style.display = 'none';
pdfButton.textContent = "Download Poem as PDF";
pdfButton.disabled = false;
}
}
// --- Attach Event Listeners ---
elements.tabButtons.forEach((button, index) => {
button.addEventListener("click", () => showTab(index));
});
if(elements.prevTabBtn) {
elements.prevTabBtn.addEventListener("click", () => { if (currentTabIndex > 0) showTab(currentTabIndex - 1); });
}
if(elements.nextTabBtn) {
elements.nextTabBtn.addEventListener("click", () => { if (currentTabIndex < elements.tabButtons.length - 1) showTab(currentTabIndex + 1); });
}
if (elements.poemTypeSelect) {
elements.poemTypeSelect.addEventListener("change", handleSelectionChange);
}
if (pdfButton) {
pdfButton.addEventListener("click", downloadPDF);
}
// --- Initial Setup ---
showTab(0);
handleSelectionChange(); // Load default template
});
${lineText.replace(/\n/g, '
')}
`;
lineCounter++;
}
renderHTML += `')}
