`;
previewOutput.innerHTML += cardHtml;
});
};
// --- Event Listeners ---
form.addEventListener("submit", findBooks);
// --- Button: Download PDF ---
pdfBtn.addEventListener("click", () => {
const { jsPDF } = window.jspdf;
const pdfArea = toolContainer.querySelector("#brf-export-area");
const fileName = 'Book_Recommendations.pdf';
// Add a title for the PDF
let titleEl = pdfArea.querySelector(".brf-pdf-title");
if (!titleEl) {
titleEl = document.createElement("h2");
titleEl.className = "brf-pdf-title";
titleEl.style.color = "#6d28d9";
titleEl.style.padding = "10px 20px 0";
titleEl.style.boxSizing = "border-box";
pdfArea.prepend(titleEl);
}
titleEl.textContent = `Your Book Recommendations`;
html2canvas(pdfArea, {
scale: 2, // Improve resolution
useCORS: true,
backgroundColor: '#ffffff'
}).then(canvas => {
// Remove the title
pdfArea.removeChild(titleEl);
const imgData = canvas.toDataURL('image/png');
const doc = new jsPDF({
orientation: 'p',
unit: 'pt',
format: 'a4'
});
const pdfWidth = doc.internal.pageSize.getWidth();
const pdfHeight = doc.internal.pageSize.getHeight();
const imgProps = doc.getImageProperties(imgData);
const imgWidth = imgProps.width;
const imgHeight = imgProps.height;
const margin = 40;
const usableWidth = pdfWidth - (2 * margin);
const ratio = usableWidth / imgWidth;
const scaledHeight = imgHeight * ratio;
if (scaledHeight < pdfHeight - (2 * margin)) {
doc.addImage(imgData, 'PNG', margin, margin, usableWidth, scaledHeight);
} else {
let position = margin;
const pageHeight = pdfHeight - (2 * margin);
let heightLeft = scaledHeight;
doc.addImage(imgData, 'PNG', margin, position, usableWidth, scaledHeight);
heightLeft -= pageHeight;
while (heightLeft > 0) {
position = margin - heightLeft;
doc.addPage();
doc.addImage(imgData, 'PNG', margin, position, usableWidth, scaledHeight);
heightLeft -= pageHeight;
}
}
doc.save(fileName);
}).catch(err => {
// Ensure title is removed even if PDF fails
if (pdfArea.contains(titleEl)) {
pdfArea.removeChild(titleEl);
}
console.error("BRF PDF Error:", err);
// alert("An error occurred while generating the PDF."); // Removed per spec
});
});
// --- Initial Load ---
// No generation on load, wait for user input.
});
