diff --git a/index.html b/index.html index 16cf12c..56fef25 100644 --- a/index.html +++ b/index.html @@ -15,6 +15,18 @@ + + + + + + + +
diff --git a/script/script.js b/script/script.js index a108184..4fa26df 100644 --- a/script/script.js +++ b/script/script.js @@ -225,6 +225,67 @@ Promise.all([ backgroundColor: darkMode ? "#121212" : "#ffffff" }); }); + + // Add Export to PDF button (reuse downloadButton's class and styles) + const exportPdfButton = document.createElement('button'); + exportPdfButton.textContent = 'Export to PDF'; + // Copy class from downloadButton if available + const downloadBtn = document.getElementById("downloadButton"); + if (downloadBtn && downloadBtn.className) { + exportPdfButton.className = downloadBtn.className; + } + // Insert immediately after downloadButton + if (downloadBtn) { + downloadBtn.insertAdjacentElement("afterend", exportPdfButton); + } else { + // fallback + document.querySelector('.controls').appendChild(exportPdfButton); + } + + // PDF export logic + exportPdfButton.addEventListener('click', async () => { + // Ensure jsPDF and svg2pdf.js are loaded + if (!(window.jspdf && window.svg2pdf)) { + alert('PDF export libraries not loaded.'); + return; + } + const { jsPDF } = window.jspdf; + const doc = new jsPDF({ + orientation: 'landscape', + unit: 'pt', + format: [960, 600] + }); + + const svgElement = document.querySelector("svg"); + const svgClone = svgElement.cloneNode(true); + svgClone.removeAttribute("style"); + svgClone.setAttribute("width", "960"); + svgClone.setAttribute("height", "600"); + // Ensure correct namespace for svg2pdf + svgClone.setAttribute("xmlns", "http://www.w3.org/2000/svg"); + + await window.svg2pdf(svgClone, doc, { + xOffset: 0, + yOffset: 0, + scale: 1 + }); + + const c = d3.select("#continentSelect").property("value"); + const s = d3.select("#sexSelect").property("value"); + const e = d3.select("#incomeSelect").property("value"); + const chartType = d3.select("#chartTypeSelect").property("value"); + + const parts = [ + "education_health", + chartType, + c !== "All" ? c : null, + s !== "All" ? s : null, + e !== "All" ? e.replace(/[^a-zA-Z0-9]+/g, "_").toLowerCase() : null + ].filter(Boolean); + const filename = parts.join("_") + ".pdf"; + + doc.save(filename); + }); }); // Update legend depending on chart type function updateLegend(chartType) {