`;
});
pdfOutputContainer.innerHTML = pdfHTML;
pdfOutputContainer.style.display = 'block'; // Make it visible for html2canvas
const { jsPDF } = window.jspdf;
const pdf = new jsPDF({
orientation: 'p',
unit: 'pt',
format: 'a4'
});
// Use a promise to ensure html2canvas completes before generating PDF
html2canvas(pdfOutputContainer, {
scale: 2, // Improve quality
useCORS: true, // If you were loading external images, though not applicable here
logging: true, // For debugging
onclone: (document) => {
// This function is called when html2canvas clones the document.
// We can apply styles here that are specific to the PDF rendering.
// For example, ensure all text is black, background is white.
let clonedBody = document.body; // Or a more specific cloned element if needed
clonedBody.style.fontFamily = "'Times New Roman', Times, serif"; // Force font for PDF
clonedBody.style.color = "#000000"; // Force text color for PDF
clonedBody.style.backgroundColor = "#ffffff"; // Force background for PDF
}
}).then(canvas => {
const imgData = canvas.toDataURL('image/png');
const imgProps = pdf.getImageProperties(imgData);
const pdfWidth = pdf.internal.pageSize.getWidth();
const pdfHeight = (imgProps.height * pdfWidth) / imgProps.width;
let position = 0;
let heightLeft = pdfHeight;
const pageHeight = pdf.internal.pageSize.getHeight() - 40; // 20pt margin top/bottom
pdf.addImage(imgData, 'PNG', 20, 20, pdfWidth - 40, pdfHeight - 40); // Add with margins
heightLeft -= pageHeight;
while (heightLeft > 0) {
position = heightLeft - pdfHeight;
pdf.addPage();
pdf.addImage(imgData, 'PNG', 20, position + 20, pdfWidth - 40, pdfHeight - 40);
heightLeft -= pageHeight;
}
pdf.save(`historical_quotes_${figureName.replace(/\s+/g, '_') || 'all'}.pdf`);
pdfOutputContainer.style.display = 'none'; // Hide it again
pdfOutputContainer.innerHTML = ''; // Clear it
}).catch(error => {
console.error("Error generating PDF:", error);
alert("There was an error generating the PDF. Please try again.");
pdfOutputContainer.style.display = 'none';
pdfOutputContainer.innerHTML = '';
});
}
